我有一个像以下一样的json
[{
"name": "abc",
"Path": "i.abc",
"count": 5347,
"subFolders": []
},
{
"name": "cde",
"Path": "i.cde",
"count": 0,
"subFolders": [{
"name": "efg",
"Path": "",
"count": 0,
"subFolders": []
},
{
"name": "hij",
"Path": "i.hij",
"count": 1,
"subFolders": []
}]
}]
我想根据“path”(其唯一)值更改“count”值。 例如,我想将路径“i.hij”的计数更改为2。 以下是我试过的代码。
var json = "above json";
for (i=0; i < json.length; i++) {
this.updateJson(json[i], path, count);
}
updateJson: function(json, path, count) {
if (json.path == path) {
json.count = count;
return json;
}
if (json.subFolders != null && json.subFolders.length > 0) {
for(j=0; j < json.subFolders.length; j++) {
this.updateJson(json.subFolders[j], path, count);
}
}
}
如何获得具有修改值的整个json?
答案 0 :(得分:1)
您的代码中存在一些问题,主要是您感到困惑Path
和path
(JavaScript区分大小写)并且您错过var
中的for
关键字(这个很微妙而且非常危险),但你离目标不远。
这是一个固定的功能:
var obj = [{
"name": "abc",
"Path": "i.abc",
"count": 5347,
"subFolders": []
},
{
"name": "cde",
"Path": "i.cde",
"count": 0,
"subFolders": [{
"name": "efg",
"Path": "",
"count": 0,
"subFolders": []
},
{
"name": "hij",
"Path": "i.hij",
"count": 1,
"subFolders": []
}]
}];
function upd(o, path, count) {
if (o.Path == path) {
o.count = count;
} else {
var arr;
if (Array.isArray(o)) arr = o;
else if (o.subFolders) arr = o.subFolders;
else return;
for(var j=0; j < arr.length; j++) {
upd(arr[j], path, count);
}
}
}
upd(obj, "i.hij", 3);
console.log(obj);
我还更改了变量名,删除了对JSON的所有引用,因为这里没有JSON。