Mithun S
Mithun S

Reputation: 418

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

Upvotes: 2

Views: 70

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

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)

Upvotes: 5

Đinh Carabus
Đinh Carabus

Reputation: 3496

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

Upvotes: 0

Related Questions