Javascript 从JSON节点JSON中的嵌套数组中提取第一个元素
我试图获取名为platforms的嵌套数组,但我只想要其中的第一个键。因此,对于数组,它应该像Javascript 从JSON节点JSON中的嵌套数组中提取第一个元素,javascript,node.js,arrays,json,Javascript,Node.js,Arrays,Json,我试图获取名为platforms的嵌套数组,但我只想要其中的第一个键。因此,对于数组,它应该像[{platforms:[windows],[windows]]}而不是[{platforms:[windows,osx,linux,null],[windows,null,null]}这是可以实现的吗?我浏览了.map和.filter,但似乎无法抓住数组的第一部分 示例数组 [{ id: 1, game: { position: 1}, platforms: [ 'windows', 'osx', '
[{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);
结果=
['windows','osx','linux'null],'windows',null,null,null],
一个简单的.map
应该做到这一点:
功能映射平台(数据){
return data.map(entry=>Array.isArray(entry.platforms)?entry.platforms[0]:“没有可用的平台数据”)
}
const data=[{id:1,游戏:{position:1},平台:['windows','osx','linux',null],标题:'xxx',用户:{url:'xxxx',名称:'xxx',id:1,},},{id:2,游戏:{position:2},平台:['windows',null,null',标题:'xxx',用户:{url:'xxxx名称:'xxx',id:2,}];
console.log(mapPlatform(数据))代码>令人沮丧!我以前做过此操作,但得到TypeError:无法读取未定义的属性“0”。但是,使用数据常量它是有效的。我试图从中提取的json输出肯定有问题。console.log(body.games.map(entry=>entry.platforms))
给了我[[['windows'、'osx'、'linux']、['windows'、'osx'、'linux']、]
但是如果我使用平台[0],我会得到未定义的内容。好吧,你添加到问题中的内容是无效的,是的。它在]
之前缺少一个}
。知道如何将它附加到我的json中使其有效吗?不管怎样,我都会把你的答案标为正确,因为你是对的!最好首先确保json是有效的,而不是手动修复它-您从哪里读取数据?