【问题标题】:Extract first element from Nested Array in JSON NodeJS从 JSON NodeJS 中的嵌套数组中提取第一个元素
【发布时间】:2020-07-07 14:03:27
【问题描述】:

我正在尝试获取名为平台的嵌套数组,但我只想要其中的第一个键。所以对于 Array 它应该是 [{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 ],

【问题讨论】:

    标签: javascript node.js arrays json


    【解决方案1】:

    一个简单的.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));

    【讨论】:

    • 令人沮丧!我以前做过这个,我得到 TypeError: Cannot read property '0' of undefined。但是,使用您的 data const 它可以工作。我试图从中提取的 json 输出一定有问题。
    • console.log(body.games.map(entry => entry.platforms)); 给我[ [ 'windows', 'osx', 'linux' ], [ 'windows', 'osx', 'linux' ], ] 但是如果我做平台[0] 我得到未定义..
    • 嗯,你添加到问题中的那个是无效的,是的。在] 之前缺少}
    • 好的关于如何将它附加到我的 json 以使其有效的任何想法?无论如何,我都会将您的答案标记为正确,因为您是对的!
    • 最好首先确保 json 是有效的,而不是手动修复它 - 你从哪里读取数据?
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多