javascriptreducearrayofarrays

Reduce Array of Object Arrays to Array of Objects


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;
});

Solution

  • 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)