从 JSON NodeJS 中的嵌套数组中提取第一个元素



我正在尝试获取名为平台的嵌套数组,但我只想要其中的第一个键。所以对于数组来说,它应该像[{platforms: [windows], [windows]]}而不是[{platforms: [windows, osx, linux, null], [windows, null, null, null]]}这甚至可以实现吗?我翻看了.map.filter,但似乎无法抓住阵列的第一块。

示例数组

[{ id: 1,
game: { position: 1},
platforms: [ 'windows', 'osx', 'linux', null ],
title: 'xxx',
user: {
url: 'xxxx',
name: 'xxx',
id: 1
}
},{ id: 2,
game: { position: 2},
platforms: [ 'windows', null, null, null, ],
title: 'xxx',
user: {
url: 'xxxx',
name: 'xxx',
id: 2
}
]

我如何在Javascript/NodeJS中处理这个问题

var result = body.games.filter(a=>a).reduce((acc, a) => {
return acc.concat(a)
}, []).map(a=>a.platforms);
console.log(result);

结果 =[ 'windows', 'osx', 'linux' null ], [ 'windows', null, null, null ],

一个简单的.map应该这样做:

function mapPlatform(data) {
return data.map(entry => Array.isArray(entry.platforms) ? entry.platforms[0] : 'no platform data available')
}
const data = [{id:1,game:{position:1},platforms:['windows','osx','linux',null],title:'xxx',user:{url:'xxxx',name:'xxx',id:1,},},{id:2,game:{position:2},platforms:['windows',null,null,null],title:'xxx',user:{url:'xxxx',name:'xxx',id:2,},}];
console.log(mapPlatform(data));

最新更新