3

我试图通过它的一个属性在 JSON 中找到一个子对象,并向该对象添加更多属性。我不确定如何使用 JQuery(或常规 javascript)来做到这一点。例如:从下面的 JSON 中,我想找到一个 id 为 123-1 的类别,然后添加另一个类别对象作为子对象。谢谢你的帮助。

JSON:

{
"result": {
    "category": 
        {
            "id": 123,
            "name": "cat1",
            "rules": [
                {
                    "rulename": "r1",
                    "regex": ""
                },
                {
                    "rulename": "r2",
                    "regex": ""
                }
            ],
            "category": 
                {
                    "id": "123-1",
                    "name": "cat1-1",
                    "rules": [
                        {
                            "rulename": "r1-1",
                            "regex": ""
                        }
                    ]
                }                
        }

}

}

Javascript:

function addSubCategory(catId, anotherCatObj) {
    //Step1: Find category object with catID in the existing json
    //Step3: add the supplied object as a child.
}
4

1 回答 1

1
function appendCategoryTo(categories, destinationCategoryId, newCategoryToAdd){
    var success = false;
    for (var i = 0; i < categories.length && !success; i++){
        var category = categories[i];
        if (category.id == destinationCategoryId){
            category.category = category.category || [];
            success = !!category.category.push(newCategoryToAdd);
        } else if (category.category) {
            success = appendCategoryTo(category.category, destinationCategoryId, newCategoryToAdd);
        }
    }
    return success;
}

您必须从obj.result.category节点开始以利用递归能力,但您可以轻松地将该方法包装在另一个中,使其更加礼貌。

但是,按原样,这是一个示例用法:

appendCategoryTo(o.result.category, '123-1', {
  id: '123-1-1',
  name: 'cat-1-1-1',
  rules: []
});
console.log(JSON.stringify(o));

它将一个新category属性作为数组添加到嵌套类别中(我假设这遵循命名法)然后将元素添加到该新数组中 - 从而为您提供:

{
  "result": {
    "category": [
      {
        "id": 123,
        "name": "cat1",
        "rules": [
          {
            "rulename": "r1",
            "regex": ""
          },
          {
            "rulename": "r2",
            "regex": ""
          }
        ],
        "category": [
          {
            "id": "123-1",
            "name": "cat1-1",
            "rules": [
              {
                "rulename": "r1-1",
                "regex": ""
              }
            ],
            "category": [              // BEGIN new addition
              {
                "id": "123-1-1",
                "name": "cat-1-1-1",
                "rules": [

                ]
              }
            ]                          // END new addition
          }
        ]
      }
    ]
  }
}

在 jsfiddle 上玩的例子,顺便说一句:http: //jsfiddle.net/cqRzX/

于 2013-07-01T17:22:13.680 回答