在嵌套json对象中查找和更新,而不更改不同子路径中的相同密钥对值
Find and update in nested json object without changing the same key-pair value in different child path
这是我上一个问题的更新在嵌套json对象中查找和更新
样本数据
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将动态生成,因此我不能在函数中有任何硬编码值
我认为您可以以某种方式使用路径来定位值,然后进行更新。我是从这篇帖子中得到这个想法的。(由@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."
}
希望它能有所启发!
相关文章:
- 从包含密钥路径的字符串中获取json值
- 如何在javascript中获取数组密钥对的json子值
- html keygen替代方案,在浏览器中生成密钥对
- 访问 JSON 中的嵌套对象(密钥对/MYSQL 数组)
- 在Javascript中生成PGP密钥对,并使用加密的PGP私钥对文本进行签名
- OpenPGP.min.js 不会生成密钥对
- 在 PHP 可读的 JavaScript 中创建 PEM 密钥对
- 如何在ajax javascript中获取数据类型json的特定值-密钥对
- 从json(不在正确的密钥对中)创建javascript对象(带有密钥对)
- 使用d3或jquery的json对象中有多少不同的密钥对值
- java.lang.RuntimeException:无法生成DH密钥对
- 在嵌套json对象中查找和更新,而不更改不同子路径中的相同密钥对值
- 如何使用Web Crypto生成密钥对,并在Firefox AddOn中访问其密钥
- 使用javascript将数组存储为json中的密钥对
- 不能使用密钥对验证Node.js加密中的签名
- jquery对象密钥对未定义
- 在MapReduce MongoDB中按密钥对数据进行分组
- Angularjs:从密钥对中解析值
- 如何返回仅包含一个特定密钥对的多个集合
- Ng-options带有一个密钥对对象数组