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'];
你不需要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)
您可以尝试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)
你可以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)
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |