这是对我之前的问题Find and update in nested json object的更新
样本数据
TestObj = {
"Categories": [{
"Products": [{
"id": "a01",
"name": "Pine",
"description": "Short description of pine."
},
{
"id": "a02",
"name": "Pine",
"description": "Short description of pine."
},
{
"id": "a03",
"name": "Poplar",
"description": "Short description of poplar."
}],
"id": "A",
"title": "Cheap",
"description": "Short description of category A."
},
{
"Product": [{
"id": "b01",
"name": "Maple",
"description": "Short description of maple."
},
{
"id": "b02",
"name": "Oak",
"description": "Short description of oak."
},
{
"id": "b03",
"name": "Bamboo",
"description": "Short description of bamboo."
}],
"id": "B",
"title": "Moderate",
"description": "Short description of category B."
}]
};
我的功能
function getObjects(obj, key, val, newVal) {
var newValue = newVal;
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val, newValue));
} else if (i == key && obj[key] == val) {
obj[key] = newValue;
}
}
return obj;
}
称为
getObjects(TestObj, 'id', 'A', 'B');
如果我要更新 id,它工作正常;因为 id 没有重复项。但是,如果我正在更新名称,则所有匹配键值对的数据都会更新。但是如何将其限制为特定的密钥对值。
我应该为函数提供什么来限制更新范围以及如何实现它。请帮我。
注意:我将要处理的 json 将动态生成,因此我不能在函数中包含任何硬编码值