【发布时间】:2020-07-02 02:55:41
【问题描述】:
我有一个要解析的 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 结构没有太多控制权,而且是 lodash 的新手。
如何解决这个变量范围问题,我可以按预期构建数组?
【问题讨论】:
-
鉴于
gamesAndCategories是一个空数组,您为什么希望能够在其中的any 索引上调用push?也许你的意思是gamesAndCategories[game] = category或只是gamesAndCategories.push(category) -
您的示例结果不是有效的 JS 结构。您能否准确说明一下结果应该是什么样的?
标签: javascript lodash