I am trying to achieve an operation where Ι am not sure where to start with. Down below is my initial object:
[
{ type: "1", name: "Anthony" },
{
type: "1",
name: "Linus",
},
{
type: "2",
name: "Sebastin",
},
]
What I am trying to achieve is to move the objects which has same type inside an array and have a key value, named title and string type. I am trying to produce an output equivalent to this and I am not sure where to begin with. Any help will be useful and appreciated. Thanks in advance <3
[
{
title: "1",
sub_items: [
{
type: "1",
name: "Anthony",
},
{
type: "1",
name: "Linus",
},
],
},
{
type: "2",
name: "Sebastin",
},
];
CodePudding user response:
You can use Array.reduce()
to group the input items by type/title and create the desired output:
const input = [{ "type":"1", "name":"Anthony" }, { "type": "1", "name": "Linus" }, { "type":"2", "name":"Sebastin" }]
const result = Object.values(input.reduce((acc, { type, name }) => {
acc[type] = acc[type] || { title: type, sub_items: [] };
acc[type].sub_items.push({ type, name });
return acc;
}, {}));
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
CodePudding user response:
You can make it with Array.reduce
const data = [
{ type: "1", name: "Anthony" },
{
type: "1",
name: "Linus",
},
{
type: "2",
name: "Sebastin",
},
];
const output = data.reduce((acc, curr, index, list) => {
const matchNodes = list.filter((node) => node.type === curr.type);
if (matchNodes.length > 1) {
const accNode = acc.find((item) => item.title === curr.type);
if (accNode) {
accNode.sub_items.push(curr);
} else {
acc.push({
title: curr.type,
sub_items: [curr],
});
}
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(output);