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;
});
1
  • 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. Commented Mar 9, 2020 at 19:19

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.