I have an Array of Object. Each Object contains another inner Array. I would like to take each inner array as outer object and put the remaining old outer elements as sub properties of newly created outer object.
Input
data = [
{
name: "Sam",
ssn: 123,
age: 25,
hobbies: [{ name: "cricket" }, { name: "football" }]
},
{
name: "John",
ssn: 234,
age: 25,
hobbies: [{ name: "cricket" }, { name: "football" }]
},
{
name: "Mathew",
ssn: 345,
age: 25,
hobbies: [{ name: "cricket" }, { name: "football" }, {name: "carroms"}]
}
];
Expected Output
[
{
name: "cricket",
person_details: [
{ name: "Sam", ssn: 123, age: 25 },
{ name: "John", ssn: 234, age: 25 },
{ name: "Mathew", ssn: 345, age: 25 }
]
},
{
name: "football",
person_details: [
{ name: "Sam", ssn: 123, age: 25 },
{ name: "John", ssn: 234, age: 25 },
{ name: "Mathew", ssn: 345, age: 25 }
]
},
{
name: "carroms",
person_details: [
{ name: "Mathew", ssn: 345, age: 25 }
]
}
]
What i have tried using Reduce as follows
this.data = this.data.reduce(
(a, x) => [...x.hobbies.map(h => ({ ...x, hobbies: [h] }))],
[]
);
hobbies:in the output? And why aren't you accessingh.namein the loop?