遍历一个内部嵌套有数组对象的 JSON 对象。 提供的 label 值是需要返回关联级别 metrics 值的标识符。如果在第二级找到标签,则找到第二级的指标,并且应该返回它
我无法获取如何遍历对象并返回特定值的逻辑
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');
考虑带有 children 的 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"
输入:“A-B-C-D”
selectedMetrics= "ma-mb-mc-md"
最佳答案
您可以执行Depth first search (DFS) 或Breadth first search (BFS) 查找任何级别的 metricValues
。
这里我使用 DFS 来查找所需的值。这适用于具有任何嵌套级别的数据。
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"} ] };
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 'A-B' = " + getMetrics(dataObj.series, 'A-B'));
console.log("selectedMetrics for 'A-B-C' = " + getMetrics(dataObj.series, 'A-B-C'));
console.log("selectedMetrics for 'A-B-C-D' = " + getMetrics(dataObj.series, 'A-B-C-D'));
console.log("selectedMetrics for '1' = " + getMetrics(dataObj.series, '1'));
关于javascript - 使用标识符遍历 JSON 对象并获取带有标识符的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57995118/