繁体   English   中英

使用array属性展平复杂对象的数组

[英]Flattening an array of complex objects with an array attribute

我想知道是否有快速解决方案(例如,使用map())将多维数组转换为一维数组,但仍保留原始数组的所有信息。

您可以通过一些循环来解决它,但是我认为必须有一个更明智的解决方案。

这里要举例说明一下:

const arr = [{
  id: 1,
  people: [
    {name: "x", surname: "x"},
    {name: "y", surname: "y"}
  ]
 },{
  id: 2,
  people: [
    {name: "a", surname: "a"},
    {name: "b", surname: "b"}
  ]
 }]

const result = [
 {id: 1, name: "x", surname: "x"},
 {id: 1, name: "y", surname: "y"},
 {id: 2, name: "a", surname: "a"},
 {id: 2, name: "b", surname: "b"}
]

Array.flatMap()与内部Array.map()可添加id

 const arr = [{"id":1,"people":[{"name":"x","surname":"x"},{"name":"y","surname":"y"}]},{"id":2,"people":[{"name":"a","surname":"a"},{"name":"b","surname":"b"}]}] const result = arr.flatMap(({ id, people }) => people.map(p => ({ id, ...p }))) console.log(result) 

如果Array.flatMap()是不是被你的目标浏览器支持,使用Array.map()并蔓延到Array.concat()

 const arr = [{"id":1,"people":[{"name":"x","surname":"x"},{"name":"y","surname":"y"}]},{"id":2,"people":[{"name":"a","surname":"a"},{"name":"b","surname":"b"}]}] const result = [].concat(...arr.map(({ id, people }) => people.map(p => ({ id, ...p })))) console.log(result) 

您可以尝试使用map()flat()

 const arr = [{ id: 1, people: [ {name: "x", surname: "x"}, {name: "y", surname: "y"} ] },{ id: 2, people: [ {name: "a", surname: "a"}, {name: "b", surname: "b"} ] }] const result = arr.map(p => { return p.people.map(pi => Object.assign(pi, {id: p.id})); }).flat(); console.log(result); 

您可以使用array.reduce为每个people创建多个条目,前提是该数组永远不会更改其形式。 有关其工作原理的更多注释直接在代码中。

 const arr = [{ id: 1, people: [ {name: "x", surname: "x"}, {name: "y", surname: "y"} ] },{ id: 2, people: [ {name: "a", surname: "a"}, {name: "b", surname: "b"} ] }] // Reduce the origianal array. const r = arr.reduce((acc, {id, people}) => { // For each people, push a new elemen to the array. return people.forEach(_people => { // the element pushed will hold the [id] and all the properties of the currently looped [people] item. acc.push(Object.assign({id}, _people)); }), acc; // <-- finally, return the accumulator for the next iteration. }, []); // <-- provide a new empty array as an initial value. console.log(r); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM