如何使用es6展平嵌套的对象数组 [英] How to flatten nested array of object using es6

查看:63
本文介绍了如何使用es6展平嵌套的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个对象数组,在其中有另一个对象数组,如何获取:

I have this array of object, within it I have another array of object, how to get:

[
  { id: "5a60626f1d41c80c8d3f8a85" },
  { id: "5a6062661d41c80c8b2f0413" },
  { id: "5a60626f1d41c80c8d3f8a83" },
  { id: "5a60626f1d41c80c8d3f8a84" }
];

发件人:

[
  {
    id: 1,
    country: [
      {
        id: "5a60626f1d41c80c8d3f8a85"
      },
      {
        id: "5a6062661d41c80c8b2f0413"
      }
    ]
  },
  {
    id: 2,
    country: [
      {
        id: "5a60626f1d41c80c8d3f8a83"
      },
      {
        id: "5a60626f1d41c80c8d3f8a84"
      }
    ]
  }
];

不使用forEach和临时变量?

当我这样做的时候:

(data || []).map(o=>{
  return o.country.map(o2=>({id: o2.id}))
})

我得到了相同的结构.

推荐答案

不需要任何ES6魔术,您只需通过串联内部country数组来减少数组.

No need for any ES6 magic, you can just reduce the array by concatenating inner country arrays.

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.reduce(
    (arr, elem) => arr.concat(elem.country), []
  )
)

如果要使用ES6功能(而不是箭头功能),请使用数组扩展而不是concat方法:

If you want an ES6 feature (other than an arrow function), use array spread instead of the concat method:

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.reduce(
    (arr, elem) => [...arr, ...elem.country], []
  )
)

注意:这些建议将在每次迭代时创建一个新数组.

Note: These suggestions would create a new array on each iteration.

为了提高效率,您必须牺牲一些优雅:

For efficiency, you have to sacrifice some elegance:

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.reduce(
    (arr, elem) => {
      for (const c of elem.country) {
        arr.push(c);
      }
      return arr;
    }, []
  )
)

这篇关于如何使用es6展平嵌套的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆