简体   繁体   English

如何将 Array 嵌套对象转换为 Array 对象?

[英]how to convert an Array nested object into an Array object?

I have an array:我有一个数组:

let testData = [
  {
    MC: "11233",
    jobid: 113331,
    list: [
      { Q1: 1113, Q2: 333, code: "thisis1" },
      { Q1: 333, Q2: 111, code: "thisis2" },
      { Q1: 333, code: "thisis3" },
    ],
  },
  {
    MC: "332211",
    jobid: 3333,
    list: [
      { Q1: 444, Q2: 555, code: "thisis4" },
    ],
  },
];

And I want to convert it into:我想把它转换成:

[
  { MC: "11233", jobid: 113331, Q1: 1113, Q2: 333, code: "thisis1" },
  { MC: "11233", jobid: 113331, Q1: 333, Q2: 111, code: "thisis2" },
  { MC: "11233", jobid: 113331, Q1: 333, code: "thisis3" },
  { MC: "332211", jobid: 3333, Q1: 444, Q2: 555, code: "thisis4" },
]

I tried to write a recursive function like this我试图写一个这样的递归函数

let newData = [];
testData.forEach((element, index) => {
  let flattedObj = {};
  deconstructeArrayObject(flattedObj, element);
});

and

const deconstructeArrayObject = (flattedObj, targetObj) => {
  let tempArr = [];
  for (let key in targetObj) {
    if (Array.isArray(targetObj[key])) {
      targetObj[key].forEach((element) => {
        tempArr.push(
          ...JSON.parse(
            JSON.stringify(
              deconstructeArrayObject(flattedObj, element, outputArray)
            )
          )
        );
      });
    } else {
      flattedObj[key] = targetObj[key];
    }
  }
  return flattedObj; // actually I want this function to return an array
};

I have no idea how should I reach my goal.我不知道我应该如何达到我的目标。 Is there any hint or suggestion?有什么提示或建议吗?

Iterate the outer array, destructuring its properties, then do the same for each inner array, pushing the data you want in your result:迭代外部数组, 解构其属性,然后对每个内部数组执行相同的操作,将所需的数据推送到结果中:

 const input = [ { MC: "11233", jobid: 113331, list: [ { Q1: 1113, Q2: 333, code: "thisis1" }, { Q1: 333, Q2: 111, code: "thisis2" }, { Q1: 333, code: "thisis3" }, ], }, { MC: "332211", jobid: 3333, list: [ { Q1: 444, Q2: 555, code: "thisis4" }, ], }, ]; const result = []; for (const {MC, jobid, list} of input) { for (const {Q1, Q2, code} of list) { result.push(({MC, jobid, Q1, Q2, code})); } } console.log(result);

How about this:这个怎么样:

 let testData = [{"MC":"11233","jobid":113331,"list":[{"Q1":1113, "test": [{ 'a' : 1}, { 'a' : 2}],"Q2":333,"code":"thisis1"},{"Q1":333,"Q2":111,"code":"thisis2"}, {"Q1":333,"code":"thisis3"}]} ,{"MC":"332211","jobid":3333,"list":[{"Q1":444,"Q2":555,"code":"thisis4"}]}] const deconstructeArrayObject = (targetObj) => { let flattedObj = {}; let tempArr = []; let arrayKeys = []; for (let key in targetObj) { // Save array keys if (Array.isArray(targetObj[key])) { arrayKeys.push(key); } else { flattedObj[key] = targetObj[key]; } } // flatten array elements arrayKeys.forEach(key => { targetObj[key].forEach((element) => { const newEl = { ...flattedObj, ...element }; // Recursion const arr = deconstructeArrayObject(newEl); tempArr.push(...arr); }); }); if(tempArr.length === 0) { return [flattedObj]; } return tempArr; } let newData = []; testData.forEach((element, index) => { const result = deconstructeArrayObject(element); newData.push(...result) }); console.log(newData)

The result will be:结果将是:

[
  {
    "MC": "11233",
    "jobid": 113331,
    "Q1": 1113,
    "Q2": 333,
    "code": "thisis1",
    "a": 1
  },
  {
    "MC": "11233",
    "jobid": 113331,
    "Q1": 1113,
    "Q2": 333,
    "code": "thisis1",
    "a": 2
  },
  {
    "MC": "11233",
    "jobid": 113331,
    "Q1": 333,
    "Q2": 111,
    "code": "thisis2"
  },
  {
    "MC": "11233",
    "jobid": 113331,
    "Q1": 333,
    "code": "thisis3"
  },
  {
    "MC": "332211",
    "jobid": 3333,
    "Q1": 444,
    "Q2": 555,
    "code": "thisis4"
  }
]

Here's a more general solution that doesn't depend on the specific key names, etc.这是一个更通用的解决方案,它不依赖于特定的键名等。

What you were missing was the answer to the subproblem: how do I merge multiple "deconstructed" objects in an array into my "flattedObj"?您缺少的是子问题的答案: how do I merge multiple "deconstructed" objects in an array into my "flattedObj"?

This is done with the call to Object.assign in the function below.这是通过在下面的函数中调用Object.assign来完成的。

function deconstructeArrayObject(obj) {
  const deconstructedObj = {};
  for (const key in obj) {
    if (Array.isArray(obj[key])) {
      Object.assign(
        deconstructedObj,
        ...obj[key].map(deconstructeArrayObject)
      );
    } else {
      deconstructedObj[key] = obj[key];
    }
  }
  return deconstructedObj;
}

// use like this
let newData = testData.map(deconstructeArrayObject);

You try this code :你试试这个代码:

let result = testData.flatMap(data => data.list.map(el => {
    let { list, ...rest } = data;
    return { ...rest, ...el };
}));

You could use Object.assing and create flattened array of new objects:您可以使用 Object.assing 并创建扁平化的新对象数组:

 let testData = [ { "MC":"11233", "jobid":113331, "list":[ {"Q1":1113,"Q2":333,"code":"thisis1"}, {"Q1":333,"Q2":111,"code":"thisis2"}, {"Q1":333,"code":"thisis3"} ]}, { "MC":"332211", "jobid":3333, "list":[ {"Q1":444,"Q2":555,"code":"thisis4"} ]} ]; let result = testData.map(d1 => { return d1.list.map(d2 => { return Object.assign({ MC: d1.MC, jobid: d1.jobid }, d2) }); }).flat(); console.log(result);

Here is an approach using flatMap, that should return what you need.这是一种使用 flatMap 的方法,它应该返回您需要的内容。

testData.flatMap(job => job.list.map(item => {
  item.MC = job.MC; 
  item.jobid = job.jobid; 
  return item; 
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM