我试图通过其中一个属性在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.
}
答案 0 :(得分: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,btw:http://jsfiddle.net/cqRzX/
上玩的例子