Tim*_*Tim 3 javascript arrays ecmascript-6
我有一个对象数组,我想返回所有id
s 的数组。例如:
const arr = [
{Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]},
{Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}
];
Run Code Online (Sandbox Code Playgroud)
我想返回:[2129, 3431, 4373, 2545, 3431]
我尝试过以下操作:
arr.map((value) => {
let newarray = [];
return newarray += value['Locations'].map(ID => ID.id);
});
Run Code Online (Sandbox Code Playgroud)
这将返回:["2129,3431,4373", "2545,3431"]
我如何组合这两个数组?
鉴于您的输入和输出不是一对一的映射,这似乎不是.map()
. 相反,我会考虑.map()
仅在内部数组上使用,但.reduce()
在外部数组上使用。
const arr = [{Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]},{Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}];
const result = arr.reduce((acc,{Locations}) => [...acc, ...Locations.map(i=>i.id)], []);
console.log(result);
Run Code Online (Sandbox Code Playgroud)
作为替代方案,您可以使用.concat()
:
const arr = [{Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]},{Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}];
const result = arr.reduce((acc,{Locations}) => acc.concat(Locations.map(i=>i.id)), []);
console.log(result);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6948 次 |
最近记录: |