2
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;
});
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Mithun S
  • 408
  • 8
  • 20
  • What should happen in the scenario that the input hobbies is an empty array? Following the logic of creating a separate row for each hobby this would mean removing the entry. – 3limin4t0r Mar 09 '20 at 19:19

2 Answers2

5

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

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);
Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44