1

我有一个如下的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": []
    }]
}]

我想根据“路径”(其唯一)值更改“计数”值。例如,我想将路径“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?

4

1 回答 1

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。

于 2013-10-10T06:16:51.263 回答