使用Javascript中的值删除父JSON

时间:2012-11-26 16:02:08

标签: javascript json

需要一些JSON帮助。 我正在使用与此类似的JSON:

{
    GreatGrandfather: {
        GrandFather: {
            Father: [
                {
                    Son: [
                        {
                            Name: "Abu Nazir",
                            Detail: {
                                Class: "3rd Grade"
                            }
                        },
                        {
                            Name: "Dexter",
                            Detail: {
                                Class: "6th Grade"
                            }
                        },
                        {
                            Name: "Rick",
                            Detail: {
                                Class: "11th Grade"
                            }
                        }
                    ]
                },
                {
                    Son: [
                         {
                            Name: "Tom Walker",
                            Detail: {
                                Class: "3rd Grade"
                            }
                        },
                        {
                            Name: "Sgt Bastisa",
                            Detail: {
                                Class: "6th Grade"
                            }
                        },
                        {
                            Name: "The Governer",
                            Detail: {
                                Class: "11th Grade"
                            }
                        }
                    ]
                }
            ]
        }
    }
}

我的问题是如何删除Class值为“3rd Grade”的Sons? 那么Abu Nazir和Tom Walker都将被删除,每个父亲只有2个儿子吗?

另外,我如何为两位父亲添加儿子?

{Name: "Stewie",Detail: {Class:"Kindergarden"}}

{Name: "Peter",Detail: {Class:"1st Grade"}}

谢谢!

2 个答案:

答案 0 :(得分:1)

var obj = JSON.parse(jsonstring);
obj.GreatGrandFather.GrandFather.Father.forEach(function(father) {
    var sons = father.Son.filter(function(son) {
        return son.Details.Class != "3rd Grade";
    });
    sons.push({Name: "Stewie",Detail: {Class:"Kindergarden"}});
    sons.push({Name: "Peter",Detail: {Class:1st Grade}});
    father.Son = sons;
});
var newjson = JSON.stringify(obj);

当然你可以使用循环而不是ES5.1-iterator函数来完成它,但我认为你得到了这个概念。

答案 1 :(得分:1)

在javascript中,您可以使用JSON.parse将您的JSON字符串转换为javascript对象,并操纵它:

var parsed = JSON.parse(JSONString);
var fathers = parsed.GreatGrandfather.GrandFather.Father;

// loop through the father array, removing sons in 3rd grade
for (var i = 0; i < fathers.length; i++) {
    var sons = fathers[i].Son;

    for (var j = 0; j < sons.length; j++) {
        // remove the 3rd graders
        if (sons[j].Detail.Class === '3rd Grade') {
            sons.splice(j, 1);
        }
    }
}

// add some sons
var newSon = {
    Name: "Stewie",
    Detail: {
        Class: "Kindergarden"
    }
};

fathers[0].Son.push(newSon);