在javascript中从嵌套对象中取出特定数组 我有一个嵌套对象:
INPUT:
{
"countryList": [
{
"label": "Australia",
"id": "555",
"productHierarchy": "ABC",
"locked": "true",
"products": [
{
"id": "342",
"label": "342- Test",
"description": "Test"
},
{
"id": "123456",
"label": "123456- Test",
"description": "Test"
}
]
},
{
"label": "Brazil",
"id": "888",
"productHierarchy": "XYZ",
"locked": "true",
"products": [
{
"id": "987",
"label": "987- Test",
"description": "Test"
},
{
"id": "567",
"label": "567- Test",
"description": "Test"
}
]
}
]
}
从这个对象我想要一个根据countryList标签的产品数组。
输出
如果我将国家/地区标签作为澳大利亚
我想:
products= [
{
"id": "342",
"label": "342- Test",
"description": "Test"
},
{
"id": "123456",
"label": "123456- Test",
"description": "Test"
}
]
请帮我解决这个问题。
答案 0 :(得分:1)
您可以使用Array#find
:
label => data.countryList.find(e => e.label == label).products;
const data = {
"countryList": [
{
"label": "Australia",
"id": "555",
"productHierarchy": "ABC",
"locked": "true",
"products": [
{
"id": "342",
"label": "342- Test",
"description": "Test"
},
{
"id": "123456",
"label": "123456- Test",
"description": "Test"
}
]
},
{
"label": "Brazil",
"id": "888",
"productHierarchy": "XYZ",
"locked": "true",
"products": [
{
"id": "987",
"label": "987- Test",
"description": "Test"
},
{
"id": "567",
"label": "567- Test",
"description": "Test"
}
]
}
]
};
const getProducts = label => data.countryList.find(e => e.label == label).products;
console.log(getProducts('Brazil'));
答案 1 :(得分:0)
其中一种方法是使用Array.prototype的filter
(如下所示)
x={countryList:[{label:"Australia",id:"555",productHierarchy:"ABC",locked:"true",products:[{id:"342",label:"342- Test",description:"Test"},{id:"123456",label:"123456- Test",description:"Test"}]},{label:"Brazil",id:"888",productHierarchy:"XYZ",locked:"true",products:[{id:"987",label:"987- Test",description:"Test"},{id:"567",label:"567- Test",description:"Test"}]}]};
function getProducts(countryName){
return x.countryList.filter(e=>e.label=countryName)[0].products;
}
console.log(getProducts("Australia"));