将对象数组的数组缩减为对象数组

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'}]}
];

想要将其生成为以下格式

[      
      {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'}]}
];

我试过下面的方法。不知道。我已经添加了 reduce 方法的一些基本功能,但接下来没有任何想法来展平它。

var flatten = data.reduce((curr, next) => {
  var temp = [];
  return (curr.hobbies = { name: "cricket" });
  temp.push(curr);
  return curr;
});

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

flatMap()是最好的选择。

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)