过滤后将数组合并为一个数组

use*_*222 13 javascript arrays typescript

我有对象数组,我只取位置数组。我的目标是将这些位置数组合并为一个数组,但是我没有这样做并得到空数组。这就是我的做法:

let results = [{
    id: '1',
    locations: ['aaaa', 'bbbbbb', 'cccccc']
  },
  {
    id: '2',
    locations: []
  },
  {
    id: '3',
    locations: ['ddd', 'aaadsad', 'sefd']
  },
  {
    id: '4',
    locations: ['ffff', 'eeee', 'sfdsfsd']
  },
];
const locationIds = [].concat.apply([], ...results.filter(s => s.locations && s.locations.length > 0).map(({
  locations
}) => ({
  locations
})));

console.log(locationIds);
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?结果应该是 ['aaaa', 'bbbbbb', 'cccccc', 'ddd', 'aaadsad', 'sefd', 'ffff', 'eeee', 'sfdsfsd'];

Mih*_*nut 8

你不需要filter这里。只需map通过传递一个回调提供的函数来使用方法,该函数应用于数组中的每个项目。

let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }, ];

const locationIds = [].concat(...results.map(s => s.locations));

console.log(locationIds);
Run Code Online (Sandbox Code Playgroud)


Mam*_*mun 6

您可以尝试flatMap()

flatMap()方法首先使用映射函数映射每个元素,然后将结果展平到一个新数组中。它与 amap()后跟 aflat()深度为 1 相同,但flatMap()通常非常有用,因为将两者合并为一种方法效率更高。

let results = [{
    id: '1',
    locations: ['aaaa', 'bbbbbb', 'cccccc']
  },
  {
    id: '2',
    locations: []
  },
  {
    id: '3',
    locations: ['ddd', 'aaadsad', 'sefd']
  },
  {
    id: '4',
    locations: ['ffff', 'eeee', 'sfdsfsd']
  },
];
const locationIds = results.flatMap(i => i.locations);
console.log(locationIds);
Run Code Online (Sandbox Code Playgroud)


Nin*_*olz 5

你可以Array#flatMap用通缉的财产。如果未给出该属性,则添加一个默认数组|| []

let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }],
    locationIds = results.flatMap(({ locations }) => locations);

console.log(locationIds);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,如果没有 polyfills,.flatMap 无法在 Edge 和 IE 中工作。 (2认同)