这是对我上一个问题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将动态生成,因此函数中不能有任何硬编码值。
发布于 2013-08-05 04:50:24
我认为您可以以某种方式使用路径来定位值,然后执行更新。我是从这个post得到这个想法的。(@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
{
"id": "a02",
"name": "Pine",
"description": "Short description of pine."
}然后,该对象将成为
{
"id": "AAA",
"name": "Pine",
"description": "Short description of pine."
}希望它能给我们一些启示!
https://stackoverflow.com/questions/17993296
复制相似问题