我试图通过其属性之一在 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.
}
最佳答案
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/
关于javascript - 使用 JSON 中的属性之一查找子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409898/