javascript 如何使用es6实现对象嵌套数组的扁平化

xt0899hw  于 2023-01-11  发布在  Java
关注(0)|答案(6)|浏览(283)

我有一个对象数组,在它里面有另一个对象数组:

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

如何像这样得到country的平面数组:

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

而不使用forEach和temp变量呢
当我这样做:

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

我又得到了同样的结构。

xxhby3vn

xxhby3vn1#

最近编辑

所有现代JS环境现在都支持Array.prototype.flatArray.prototype.flatMap

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

console.log(
  data.flatMap(
    (elem) => elem.country
  )
)

旧答案

不需要任何ES6魔法,您只需通过连接内部的country数组来减少数组。

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方法:

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], []
  )
)

注意:这些建议会在每次迭代中创建一个新数组。
为了提高效率,您不得不牺牲一些优雅:

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;
    }, []
  )
)
vatpfxk5

vatpfxk52#

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

const countryIds = raw
                    .map(x => x.country)
                    .reduce((acc, curr) => {
                      return [
                        ...acc, 
                        ...curr.map(x => x.id)
                      ];
                    }, []);
console.log(countryIds)
xriantvc

xriantvc3#

这样就可以工作了,只需将解决方案返回的嵌套数组连接起来

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

//If you want an array of country objects
console.log([].concat.apply(...(arr || []).map(o=> o.country)))

//If you can an array od country ids
console.log([].concat.apply(...(arr || []).map(o=> o.country.map(country => country.id))))
suzh9iv8

suzh9iv84#

古普塔的解决方案将适用于这种情况。但我想提供其他解决方案。

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

const ids = arr.reduce(
  (acc, {country}) => [
    ...acc,
    ...country.map(({id}) => ({
      id
    }))
  ],
  []
);
console.log(ids);
zqry0prt

zqry0prt5#

对于JSON字符串数据,也可以在解析过程中完成:

var ids = [], json = '[{"id":1,"country":[{"id":"5a60626f1d41c80c8d3f8a85"},{"id":"5a6062661d41c80c8b2f0413"}]},{"id":2,"country":[{"id":"5a60626f1d41c80c8d3f8a83"},{"id":"5a60626f1d41c80c8d3f8a84"}]}]';

JSON.parse(json, (k, v) => v.big && ids.push(v));

console.log( ids );
6pp0gazn

6pp0gazn6#

我不知道为什么没有人提到flat()(可能是对于大型阵列,它可能性能较差)

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

相关问题