var 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'}]}
];
want to generate this to following format
[
{name:'Sam',ssn:123, age:25,hobbies:[{name:'cricket'}]},
{name:'Sam',ssn:123, age:25,hobbies:[{name:'football'}]},
{name:'John',ssn:234, age:25,hobbies:[{name:'cricket'}]},
{name:'John',ssn:234, age:25,hobbies:[{name:'football'}]},
{name:'Mathew',ssn:345, age:25,hobbies:[{name:'cricket'}]},
{name:'Mathew',ssn:345, age:25,hobbies:[{name:'football'}]}
];
I have tried the following way. not getting any idea. I have added some basic functionality of reduce method but going forward not getting any idea to flatten it.
var flatten = data.reduce((curr, next) => {
var temp = [];
return (curr.hobbies = { name: "cricket" });
temp.push(curr);
return curr;
});
flatMap()
is the best choice here.
var 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'}]} ]; const res = data.flatMap(x => x.hobbies.map(h => ({...x, hobbies: [h]}))); console.log(res)
var 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'}]} ]; data = data.reduce((a, x) => [ ...a, ...x.hobbies.map(h => ({...x, hobbies: [h]})) ], []); console.log(data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.