There is an array for each id key that is not needed. That is kind of a group break.
const header = [
[
{ id: "1",
text: "A",
},
],
[
{ id: "2",
text: "B",
array:[1,2,3],
},
{ id: "2",
text: "B1",
},
],
[
{ id: "3",
text: "A",
},
],
];
The result should be that below. The array between the same id should disapear. Only one array that contains the data as objects should remain.
const header = [
{ id: "1",
text: "A",
},
{ id: "2",
text: "B",
array:[1,2,3],
},
{ id: "2",
text: "B1",
},
{ id: "3",
text: "A",
},
];
CodePudding user response:
What you're trying to archive is called flatten.
JavaScript has the build in method to archive this: Array.prototype.flat()
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Example (taken from the source above)
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
CodePudding user response:
You might have to use nested loops, since every index of an array is also an array and push items in an new array.
const header = [
[{ id: '1', text: 'A' }],
[
{ id: '2', text: 'B', array: [1, 2, 3] },
{ id: '2', text: 'B1' },
],
[{ id: '3', text: 'A' }],
];
const newHeader = [];
header.forEach(headerItems => {
headerItems.forEach(headerItem => {
newHeader.push(headerItem)
});
})
console.log(newHeader);