在嵌套的json对象中查找和更新 [英] Find and update in nested json object
本文介绍了在嵌套的json对象中查找和更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用此代码从 sJhonny的问题中找到json对象所需的部分
数据样本
TestObj = {
"Categories": [{
"Products": [{
"id": "a01",
"name": "Pine",
"description": "Short description of pine."
},
{
"id": "a02",
"name": "Birch",
"description": "Short description of birch."
},
{
"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) {
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));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
使用如下:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
此代码用于从源中选择匹配的片段。但我想要的是用新值更新源对象并检索更新的源对象。
This code is to select matching piece from the source. But what I want is to update the source object with new value and retrieve the updated source object.
我想要类似
getObjects(TestObj, 'id', 'A', 'B'); // Returns source with updated value. (ie id:'A' updated to id:'B' in the returned object)
我的代码
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));
} else if (i == key && obj[key] == val) {
obj[key] = 'qwe';
}
}
return obj;
}
如果我给 obj [key] = 'qwe';
但如果我将代码更改为 obj [key] = newValue;
更新为未定义。
This works if i give obj[key] = 'qwe';
but if i change the code into obj[key] = newValue;
its updated as undefined.
为什么会这样?
推荐答案
你忘了在嵌套调用中传递newValue
You forgot to pass newValue in the nested call
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] = 'qwe';
}
}
return obj;
}
这篇关于在嵌套的json对象中查找和更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文