【问题标题】:Convert Array to nested Object Array [duplicate]将数组转换为嵌套对象数组
【发布时间】:2021-05-17 08:44:29
【问题描述】:

我有一个问题,如何将数组转换为嵌套对象数组? IE。我有以下数组:

const myArray = [
    { "depart_id": 1, "depart_name": "computer science", "faculty_name": "faculty of natural science", "faculty_id": 1 },
    { "depart_id": 2, "depart_name": "computer programming", "faculty_name": "faculty of natural science", "faculty_id": 1 },
    { "depart_id": 3, "depart_name": "chemical engineering", "faculty_name": "faculty of engieering", "faculty_id": 2 },
    { "depart_id": 4, "depart_name": "marketing", "faculty_name": "faculty of business", "faculty_id": 3 },
]

请解释一下如何将这些数组转换为以下格式:

const resultArray = [
    {
        "faculty_id": 1,
        "faculty_name": "faculty of natural science",
        "department": [
            {
                "depart_id": 1,
                "depart_name": "computer science"
            },
            {
                "depart_id": 2,
                "depart_name": "computer programming"
            }
        ]
    },
    {
        "faculty_id": 2,
        "faculty_name": "faculty of engieering",
        "department": [
            {
                "depart_id": 3,
                "depart_name": "chemical engineering"
            }
        ]
    },
    {
        "faculty_id": 3,
        "faculty_name": "faculty of business",
        "department": [
            {
                "depart_id": 4,
                "depart_name": "marketing"
            }
        ]
    }
]

【问题讨论】:

  • 什么不起作用?请添加您的代码。

标签: javascript arrays lodash


【解决方案1】:

const myArray = [{
    "depart_id": 1,
    "depart_name": "computer science",
    "faculty_name": "faculty of natural science",
    "faculty_id": 1
  },
  {
    "depart_id": 2,
    "depart_name": "computer programming",
    "faculty_name": "faculty of natural science",
    "faculty_id": 1
  },
  {
    "depart_id": 3,
    "depart_name": "chemical engineering",
    "faculty_name": "faculty of engieering",
    "faculty_id": 2
  },
  {
    "depart_id": 4,
    "depart_name": "marketing",
    "faculty_name": "faculty of business",
    "faculty_id": 3
  },
];

const result = [];

myArray.forEach(function(arr) {
  const dept = result.find(res => res.faculty_id === arr.faculty_id);

  const {
    faculty_id,
    faculty_name,
    depart_id,
    depart_name
  } = arr;

  if (!dept) {
    result.push({
      faculty_id,
      faculty_name,
      department: [{
        depart_id,
        depart_name
      }]
    })
  } else {
    dept.department.push({
      depart_id,
      depart_name
    })
  }
})

console.log(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-26
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多