我嵌套了 JSON,如下所示:
{
"fields": {
"type": "custom",
"level1": {
"type": "custom"
},
"level2": {
"type": "custom",
"level3": {
"type": "custom"
},
"level31": {
"type": "notcustom"
}
}
}
}
我想提取所有具有键 type
的值
我想要的输出是:
{
"fields":"custom",
"level1":"custom",
"level2":"custom"
}
最佳答案
我尝试使用递归方法使它变得简单。首先检查它是否是一个对象。如果它是一个对象,则再次调用传递该对象的函数。
否则检查键和适当的值是否存在。将其填充到结果对象中并返回。
var object = {
"fields": {
"type": "custom",
"level1": {
"type": "custom"
},
"level2": {
"type": "custom",
"level3": {
"type": "custom"
},
"level31": {
"type": "notcustom"
}
}
}
};
function recursiveIterator(object, needle, value, result) {
var result = result || {};
for (var key in object) {
if (object[key][needle] === value) {
result[key] = object[key][needle];
}
if (typeof object[key] === "object") {
recursiveIterator(object[key], needle, value, result);
}
}
return result;
}
document.getElementById("result").textContent = JSON.stringify(recursiveIterator(object, "type", "custom"));
<div id="result"></div>
这是一种非常通用的方法。您可以传递 key
,例如在本例中为 type
以及您要匹配的值,在本例中为 custom
。
关于javascript - 返回嵌套 JSON 中包含特定键的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29494032/