I have an array like so
let items = [
{name: "1"},
{name: "2"},
{name: "3"},
{unwrap: true,
items: [
{name: "4"},
{name: "5"},
{name: "6"},
]
},
{name: "7"},
]
How can I flatten the unwrap object to get the following output?
items = [
{name: "1"},
{name: "2"},
{name: "3"},
{name: "4"},
{name: "5"},
{name: "6"},
{name: "7"},
]
I thought I could do something like this:
items.map(item => {
if(item.hasOwnProperty("unwrap")){
return ... item.items
}
return item
})
However the ...s don't work as a return value.
I have come up with the somewhat clunky using a second array like so:
let output = []
items.forEach((item) => {
if (!item) {
return;
}
if (item.hasOwnProperty("unwrap")) {
return output.push(...item.contents);
}
return output.push(item);
});
You can rely on flatMap:
items.flatMap((x) => {
if (!x.unwrap) {
return x;
}
return x.items;
});
flatMap is what you need.
const items=[{name:"1"},{name:"2"},{name:"3"},{unwrap:!0,items:[{name:"4"},{name:"5"},{name:"6"}]},{name:"7"}];
const result = items.flatMap(item => {
if (item.hasOwnProperty('unwrap')) {
return item.items;
}
return item;
});
console.log(result);
Another way using reduce()
let items = [{name: "1"}, {name: "2"}, {name: "3"}, {unwrap: true, items: [{name: "4"}, {name: "5"}, {name: "6"}, ] }, {name: "7"}, ];
const res = items.reduce((p, c) => p.concat(c.items || c), []);
console.log(res);
Since obj.items won't exist on the regular objects, we can use the || operator to get the desired items, then concat those to the final array.