[英]With an identifier traverse through a JSON object and get a specific value with the identifier
遍歷其中包含嵌套數組對象的JSON對象。 提供了標簽值,該標簽值是需要返回相關級別指標值的標識符。 如果在第二層找到標簽,則在第二層找到指標,並應將其返回
我無法獲得關於如何遍歷對象並返回特定值的邏輯
function getMetrics(arr, label) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].label === label) {
return arr[i].metricsValue;
} else if (arr[i].children) {
return getMetrics(arr[i].children, label);
}
}
return "Not found";
}
const selectedMetrics = getMetrics(dataObj.series, '1');
考慮帶有子對象的JSON對象,該子對象指定當前級別的子級別。
const dataObj = {
series: [
{
label: "A",
metricsValue: "ma",
children: [
{
label: "A-B",
value: 6,
metricsValue: "ma-mb"
},
{
label: "A-B-C",
metricsValue: "ma-mb-mc",
children: [
{
label : "A-B-C-D",
value: 6,
metricsValue: "ma-mb-mc-md"
}
]
}
]
},
{
label: "1",
metricsValue: "m1",
}
]
};
預期結果:輸入為“ 1”時,應返回
selectedMetrics= "m1"
輸入:“ ABCD”
selectedMetrics= "ma-mb-mc-md"
您可以執行深度優先搜索 (DFS)或寬度優先搜索 (BFS)來查找任何級別的metricValues
。
在這里,我使用DFS查找所需的值。 這適用於具有任何嵌套級別的數據。
const dataObj = { series: [ { label: "A", metricsValue: "ma", children: [ { label: "AB", value: 6, metricsValue: "ma-mb" }, { label: "ABC", metricsValue: "ma-mb-mc", children: [ { label: "ABCD", value: 6, metricsValue: "ma-mb-mc-md" } ] } ] }, { label: "1", metricsValue: "m1"} ] }; function getMetrics(arr, label) { var result; for (let i = 0; i < arr.length; i++) { if (arr[i].label === label) { return arr[i].metricsValue; } else if (arr[i].children) { result = getMetrics(arr[i].children, label); if (result) { return result; } } } return null; } console.log("selectedMetrics for 'A' = " + getMetrics(dataObj.series, 'A')); console.log("selectedMetrics for 'AB' = " + getMetrics(dataObj.series, 'A-B')); console.log("selectedMetrics for 'ABC' = " + getMetrics(dataObj.series, 'AB-C')); console.log("selectedMetrics for 'ABCD' = " + getMetrics(dataObj.series, 'ABC-D')); console.log("selectedMetrics for '1' = " + getMetrics(dataObj.series, '1'));
您正在傳遞值,因此請使用它代替字符串,並且您不會訪問子節點。
for(var i=0; i< arr.length;i++){
const x = arr[i];
if (x.children.label === value) {
console.log(x.metricValue)
}else{
x.forEach(element => {
if (element.children.label === value) {
console.log(element.metricValue)
}else{
element.forEach(secondEl =>{
if (secondEl.children.label === value) {
console.log(secondEl.metricValue)
}
})
}
});
}
}
您可以創建一種更優雅的方法來遍歷子節點,但這可能會幫助您
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.