Sample Data
const data = [{ id: 1,iitems: [{ id: 1, name: 'R1'}]},{id: 2, items: [{ id: 1, name: 'R2'},{ id: 1, name: 'R3'}]}];
data.map((item) => item.items).data.reduce((acc, curr) => acc.concat(curr), [])
console.log(data)
What I'm trying to do here is to merge the nested to one array. but the output is like this.
data = [
{ id: 1, name: 'R1'},
{ id: 1, name: 'R2'},
{ id: 1, name: 'R3'}]
Expected output:
data = [
{ id: 1 },
{ id: 1, name: 'R1' },
{ id: 2 },
{ id: 1, name: 'R2'},
{id: 1, name: 'R3'}
];
CodePudding user response:
You can "flatten" your structure like this:
let flatten = obj => [obj, ...(obj.items || []).flatMap(flatten)]
let result = data.flatMap(flatten)
Note that this performs "deep" flattening, that is, works with sub-objects containing deeper items
arrays.
CodePudding user response:
You can use .flatMap()
where you destructure items
and the rest of the object properties into their own object (r
). Then you can return an array from the .flatMap()
to merge all items together into the one resulting array:
const data = [{ id: 1,items: [{ id: 1, name: 'R1'}]},{id: 2, items: [{ id: 1, name: 'R2'},{ id: 1, name: 'R3'}]}];
const res = data.flatMap(({items, ...r}) => [r, ...items]);
console.log(res);
CodePudding user response:
use this:
const newData = data.map(item => [{id: item.id}, ...item.items]).flat(1)
CodePudding user response:
Be carefull, you have iitems and items, name error, but here is an aproach:
var data = [{ id: 1,items: [{ id: 1, name: 'R1'}]},{id: 2, items: [{ id: 1, name: 'R2'},{ id: 1, name: 'R3'}]}];
var dataNew = [];
data.forEach(element => {
dataNew.push({
id: element.id
})
if(element.items.length>0){
element.items.forEach(elementInner => {
dataNew.push({
id: element.id,
name:elementInner.name
})
})
}
})
console.log(dataNew)
Output:
0: Object { id: 1 }
1: Object { id: 1, name: "R1" }
2: Object { id: 2 }
3: Object { id: 2, name: "R2" }
4: Object { id: 2, name: "R3" }
length: 5