Javascript 过滤后将数组合并到一个数组

Javascript 过滤后将数组合并到一个数组,javascript,arrays,typescript,Javascript,Arrays,Typescript,我有一个对象数组,我只取数组中的位置。我的目标是将这些位置数组合并到一个数组中,但我没有这样做,得到的是空数组。我就是这样做的: let结果=[{ id:'1', 地点:['aaaa','bbbbbb','CCCC'] }, { id:'2', 地点:[] }, { id:'3', 地点:['ddd','aaadsad','sefd'] }, { id:'4', 地点:['ffff','eeee','sfdsfsd'] }, ]; const locationIds=[].concat.app

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

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

console.log(locationid)这里不需要
过滤器。只需使用
map
方法,传递一个回调函数,该函数应用于数组中的每个项

let results=[{id:'1',locations:['aaaa','bbbbbbbb','cccccccc']},{id:'2',locations:['ddd','aaadsad','sefd']},{id:'4',locations:['ffff','eeee','sfdsfsd']},];
const locationIds=[].concat(…results.map(s=>s.locations));
console.log(locationid)您可以尝试:

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

let结果=[{
id:'1',
地点:['aaaa','bbbbbb','CCCC']
},
{
id:'2',
地点:[]
},
{
id:'3',
地点:['ddd','aaadsad','sefd']
},
{
id:'4',
地点:['ffff','eeee','sfdsfsd']
},
];
const locationIds=results.flatMap(i=>i.locations);
console.log(locationid)你可以用通缉犯的财产抢劫一个。如果未指定属性,请添加默认数组
| |[]

let results=[{id:'1',位置:['aaaa','bbbbbbbb','cccccc']},{id:'2',位置:[]},{id:'3',位置:['ddd','aaadsad','sefd']},{id:'4',位置:['ffff',eee',sfdsfsd']},
locationIds=results.flatMap(({locations})=>locations);
console.log(locationid)
.as控制台包装{max height:100%!important;top:0;}
还可以使用Array.prototype中的函数进行求解

var newResults = results.reduce(function(acc, curr) {
    return acc.concat(curr.locations)
  },[]
)


希望这有帮助

我花了太多时间在这上面,没有发布我自己的解决方案——这对我来说是一个有趣的难题,尽管其他答案无疑更具表现力和可读性。它使用了和你原来的帖子相同的策略,这可能有助于指出哪里出了问题

const locationIds = [].concat
                    .apply([], results.filter(result => 
                    result.locations && result.locations.length > 0)
                    .map(result => { return result.locations }));

值得一提。如果没有多边形填充,flatMap在Edge和IE中不起作用。@user122222,不客气!您可以创建自己的
flatMap
实现,如下所示: