将对象数组的数组简化为对象数组

Posted

技术标签:

【中文标题】将对象数组的数组简化为对象数组【英文标题】:Reduce Array of Object Arrays to Array of Objects 【发布时间】:2020-03-09 19:02:46 【问题描述】:
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;
);

【问题讨论】:

输入hobbies为空数组的场景应该怎么办?按照为每个爱好创建单独行的逻辑,这意味着删除条目。 【参考方案1】:

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)

【讨论】:

【参考方案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']
];

data = data.reduce((a, x) => [
  ...a, 
  ...x.hobbies.map(h => (...x, hobbies: [h]))
], []);

console.log(data);

【讨论】:

以上是关于将对象数组的数组简化为对象数组的主要内容,如果未能解决你的问题,请参考以下文章

使用 vue.js 将二维关联数组转换为 Object

built_value 如何将 json 数组反序列化为对象数组?

无法将 JSON 数组反序列化为 C# 对象 [关闭]

php将对象数组转成普通数组

Json.NET:将嵌套数组反序列化为强类型对象

如何将对象的json数组反序列化为字典[重复]