提问者:小点点

节点中从嵌套数组中提取第一个元素


我试图获取名为platforms的嵌套数组,但我只需要其中的第一个键。 所以对于数组,它应该像[{platforms:[windows],[windows]]}而不是[{platforms:[windows,osx,linux,null],[windows,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);

Result=['windows','osx','linux'null],['windows',null,null],


共1个答案

匿名用户

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

null

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));