我有这个嵌套对象(json):
const json = {
"application": {
"App1": {
"cats": [
1
]
},
"App2": {
"cats": [
3
]
},
"App3": {
"cats": [
1,
2
]
}
},
"categories": {
"1": {
"name": "FirstCategory"
},
"2": {
"name": "SecondCategory"
},
"3": {
"name": "ThirdCategory"
}
}
};
该对象具有两个主要属性:application
和categories
。
我想映射到application
的{{1}}数组上,并获取cats
数组的每个元素的name
属性。
所以最终结果应该像这样:
cats
我尝试使用{
"App1": "FirstCategory",
"App2": "ThirdCategory",
"App3": "FirstCategory, ThirdCategory"
}
函数,但是主要困难在于map
属性applicaiton
内部是数组(可以有多个值)。所以下面的代码不起作用:
cats
答案 0 :(得分:2)
您可以使用Array.reduce来解决问题。
const json = {
"application": {
"App1": {
"cats": [
1
]
},
"App2": {
"cats": [
3
]
},
"App3": {
"cats": [
1,
2
]
}
},
"categories": {
"1": {
"name": "FirstCategory"
},
"2": {
"name": "SecondCategory"
},
"3": {
"name": "ThirdCategory"
}
}
};
//Getting Application object
const application = json.application
//Getting Categories object
const categories = json.categories
//initializing reduce with a blank object and pushing all the keys of the application object
//Looping over keys of application object
const requiredOutput = Object.keys(application).reduce((out, appKey) => {
//Setting value based on categories name
out[appKey] = application[appKey].cats.map(id => categories[id].name)
return out
}, {})
console.log(requiredOutput)
PS:您可以引用this gist来安全地读取嵌套对象。
答案 1 :(得分:1)
尝试一下。
for(let val in json.application){
json.application[val] = json.application[val].cats.map(cat => json.categories[cat].name).join(",")
}
答案 2 :(得分:1)
const result = Object.keys(json.application).reduce((a,key) => {
a[key] = json.application[key].cats
.map(cat => json.categories[cat].name)
.join(", ")
return a;
}, {})