在嵌套的json对象中查找和更新,而无需在其他子路径中更改相同的密钥对值 [英] Find and update in nested json object without changing the same key-pair value in different child path
问题描述
这是我以前的问题的更新在嵌套中查找和更新json对象
This is an update to my previous question 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没有重复项.但是,如果我要更新名称,那么所有匹配键值对的数据都会更新.但是如何将其约束为特定的密钥对值.
It works fine if I'm going to update id; since id don't have duplicates. But if I'm updating name all data matching key value pair is updated. But how to constrain it into a particular key-pair value.
我应该提供什么功能来约束更新范围以及如何实现它.请帮助我.
What shall i provide to the function to constrain the update scope and how to implement it. Please help me.
注意::我将操作的json是动态生成的,因此该函数中没有任何硬编码值
Note: The json that I will b manipulating will be dynamically generated so I can't have any hard coded value in the function
推荐答案
我认为您可以以某种方式使用路径来定位值,然后进行更新.我从帖子中得到了这个主意. (由@shesek回答)
I think you can somehow use a path to locate the value and then do the update. I got the idea from this post. (answered by @shesek)
var getPath = function (obj, path, newValue) {
var parts = path.split('.');
while (parts.length > 1 && (obj = obj[parts.shift()]));
obj[parts.shift()] = newValue;
return obj;
}
console.log(getPath(TestObj, 'Categories.0.Products.1.id', 'AAA'))
console.log(TestObj)
因此,您可以传递对象的路径,例如,如果要将以下对象的id
更新为"AAA",则可以传递Categories.0.Products.1.id
So you can pass in the path to the object, for example, if you want to update the id
of the following object to "AAA", you can pass in Categories.0.Products.1.id
{
"id": "a02",
"name": "Pine",
"description": "Short description of pine."
}
然后,对象将变为
{
"id": "AAA",
"name": "Pine",
"description": "Short description of pine."
}
希望它可以为您带来启发!
Hope it can shed some light on!
这篇关于在嵌套的json对象中查找和更新,而无需在其他子路径中更改相同的密钥对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!