我用這個代碼從sJhonny's Question查找和嵌套的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."
}]
};
功能找到JSON對象所需的部分找到
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
此代碼是從源代碼中選擇匹配的部分。但我想要的是用新值更新源對象並檢索更新後的源對象。
我想是這樣
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;
其爲未定義更新。
這是爲什麼?
OBJ [關鍵] =的newval? – Virus721
其他條件是否正確? – Okky
我不明白你想要做什麼。您是否想在檢索源對象的同時更新源對象? OO – Virus721