简体   繁体   English

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

[英]Extract first element from Nested Array in JSON NodeJS

I'm trying to grab the nested array called platforms, but i only want the first key in there.我正在尝试获取称为平台的嵌套数组,但我只想要那里的第一个键。 So for the Array it should be like [{platforms: [windows], [windows]]} instead of [{platforms: [windows, osx, linux, null], [windows, null, null, null]]} Is this even achievable? So for the Array it should be like [{platforms: [windows], [windows]]} instead of [{platforms: [windows, osx, linux, null], [windows, null, null, null]]} Is this甚至可以实现? I looked through .map and .filter but can't seem to just grab the first piece of the array.我查看了.map.filter但似乎不能只抓住数组的第一块。

Example ARRAY示例数组

[{ 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
}
]

How can I handle this in Javascript / NodeJS我如何在 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, null ], Result = [ 'windows', 'osx', 'linux' null ], [ 'windows', null, null, null ],

A simple .map should do this:一个简单的.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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM