我正在努力从下面的JSON输入中使用JSON.parse获得所需的输出。我正在使用javascript,基本上,我需要根据类别名称获取每个类别的ID。我将名称作为系统中的条件,现在我需要获取所有3个ID。
JSON数据:
{"TokenID": "9FBBD91BBB",
"OrgID": 0,
"OutputObject": {
"SUBROOT": [{
"Parent Category": "Hardware",
"Parent CategoryId": 2,
"Sub Category": "Computer",
"Sub CategoryId ": 3,
"Child Category": "CPU",
"Child CategoryId": 4,
"Tenant": "IT"
},
{
"Parent Category": "Hardware",
"Parent CategoryId": 2,
"Sub Category": "Router",
"Sub CategoryId ": 3,
"Child Category": "Cisco",
"Child CategoryId": 6,
"Tenant": "IT"
},
{
"Parent Category": "Software",
"Parent CategoryId": 7,
"Sub Category": "Windows",
"Sub CategoryId ": 8,
"Child Category": "Operating System",
"Child CategoryId": 9,
"Tenant": "IT"
},
{
"Parent Category": "Software",
"Parent CategoryId": 7,
"Sub Category": "ERP",
"Sub CategoryId ": 10,
"Child Category": "SAP",
"Child CategoryId": 11,
"Tenant": "IT"
}]
}
}
查询
{
"Parent Category": "Hardware",
"Sub Category": "Router",
"Child Category": "Cisco"
}
所需的输出:
"Parent CategoryId": 2,
"Sub CategoryId ": 3,
"Child CategoryId": 6
答案 0 :(得分:1)
我的建议是将这两个要求分开。首先获取所有与查询匹配的条目,然后选择所需的键。例如:
// match query against every entry in input
const match = (query, input) => input.filter((entry) => Object.entries(query).every(([k, v]) => entry[k] === v));
// pluck only the required keys from every entry in input
const pluck = (keys, input) => input.map((entry) => keys.reduce((acc, k) => ({...acc, [k]: entry[k]}), {}));
//////////
const input = {
"TokenID": "9FBBD91BBB",
"OrgID": 0,
"OutputObject": {
"SUBROOT": [
{
"Parent Category": "Hardware",
"Parent CategoryId": 2,
"Sub Category": "Computer",
"Sub CategoryId ": 3,
"Child Category": "CPU",
"Child CategoryId": 4,
"Tenant": "IT"
},
{
"Parent Category": "Hardware",
"Parent CategoryId": 2,
"Sub Category": "Router",
"Sub CategoryId": 3,
"Child Category": "Cisco",
"Child CategoryId": 6,
"Tenant": "IT"
},
{
"Parent Category": "Software",
"Parent CategoryId": 7,
"Sub Category": "Windows",
"Sub CategoryId": 8,
"Child Category": "Operating System",
"Child CategoryId": 9,
"Tenant": "IT"
},
{
"Parent Category": "Software",
"Parent CategoryId": 7,
"Sub Category": "ERP",
"Sub CategoryId": 10,
"Child Category": "SAP",
"Child CategoryId": 11,
"Tenant": "IT"
}
]
}
};
const query = {
"Parent Category": "Hardware",
"Sub Category": "Router",
"Child Category": "Cisco"
};
// apply
const matches = match(query, input.OutputObject.SUBROOT);
const reduced = pluck(['Parent CategoryId', 'Sub CategoryId', 'Child CategoryId'], matches);
console.log(reduced);