我有一个json blob,我正试图解析,但我遇到了麻烦。下面是json的例子:
let subscriptions = {
"Channel-416025343279890452":{
"PC":{
"Game-1":[
1
],
"Game-2":[
1
]
},
"XBOX":{
"Game-2":[
1
],
"Game-3":[
1,
3
],
"Game-4":[
4,
5,
]
}
}
}我的目标是最终得到一个集合来识别每个游戏的每个平台,比如.
[
"Game-1":[
"PC",
"XBOX",
]
]我的项目使用lodash,所以我希望能用这个库得到一个更易读的解决方案.
let subs = this.subscriptions[this.channel.id];
var gamesAndCategories = [];
_.forOwn(subs, (gamesAndInterests, category) => {
_.forOwn(gamesAndInterests, (interestId, game) => {
gamesAndCategories[game].push(category);
});
});
console.log(gamesAndCategories);我遇到TypeError: Cannot read property 'push' of undefined了。我尝试将箭头函数替换为function () {},但没有运气。我还想知道是否有一种更简单的方法来提取这些数据?我对json的结构并没有太大的控制,而且我是新来的房客。
如何解决这个变量范围问题,在那里我可以像我所期望的那样构建数组?
发布于 2020-07-02 03:36:56
您可以使用减少操作收集所有游戏到平台的数据(不需要Lodash )。
的平台数组收集游戏所键对象(或Map)中的数据。
const sub = {"PC":{"Game-1":[1],"Game-2":[1]},"XBOX":{"Game-2":[1],"Game-3":[1,3],"Game-4":[4,5]}}
const gamesAndCategories = Object.entries(sub)
.reduce((map, [ platform, gameObj ]) => {
Object.keys(gameObj).forEach(game => {
const games = map[game] || (map[game] = [])
games.push(platform)
})
return map
}, Object.create(null))
console.log(gamesAndCategories)
发布于 2020-07-02 03:30:01
这不是范围问题。您应该指定gamesAndCategories[game]的初始值。
let subscriptions = {
"Channel-416025343279890452":{
"PC":{
"Game-1":[
1
],
"Game-2":[
1
]
},
"XBOX":{
"Game-2":[
1
],
"Game-3":[
1,
3
],
"Game-4":[
4,
5
]
}
}
}
let subs = subscriptions["Channel-416025343279890452"];
var gamesAndCategories = {};
_.forOwn(subs, (gamesAndInterests, category) => {
_.forOwn(gamesAndInterests, (interestId, game) => {
if (gamesAndCategories[game] == undefined) {
gamesAndCategories[game] = []
}
gamesAndCategories[game].push(category);
});
});
console.log(gamesAndCategories);<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
https://stackoverflow.com/questions/62688250
复制相似问题