使用javascript

时间:2016-03-15 06:38:36

标签: javascript angularjs json replace

这是JSON replacement的后续问题  在那里我无法得到适当的回应。因此,我发布了一个更好的例子。

var beforeReplacement=[
    {
        "Name": "app1",
        "id": "1",
        "groups": [
            {
                "id": "test1",
                "name": "test grp45",
                "desc": "this is a test group"
            },
            {
                "id": "test2",
                "name": "test group 2",
                "desc": "this is another test group"
            }
        ]
    },
    {
        "Name": "app2",
        "id": "2",
        "groups": [
            {
                "id": "test3",
                "name": "test group 4",
                "desc": "this is a test group"
            },
            {
                "id": "test4",
                "name": "test group 4",
                "desc": "this is another test group"
            }
        ]
    }
]


changed object:   
 [
        {
            "Name": "app2",
            "id": "2",
            "groups": [
                {
                    "id": "test3",
                    "name": "changed test group 4",
                    "desc": "this is a test group"
                }

            ]
        }
    ]





 var afterReplacement=[
        {
            "Name": "app1",
            "id": "1",
            "groups": [
                {
                    "id": "test1",
                    "name": "test grp45",
                    "desc": "this is a test group"
                },
                {
                    "id": "test2",
                    "name": "test group 2",
                    "desc": "this is another test group"
                }
            ]
        },
        {
            "Name": "app2",
            "id": "2",
            "groups": [
                {
                    "id": "test3",
                    "name": "changed test group 4",
                    "desc": "this is a test group"
                },
                {
                    "id": "test4",
                    "name": "test group 4",
                    "desc": "this is another test group"
                }
            ]
        }
    ]

我在 var beforeReplacement 中更改了名称,并提到了我将在更改后收到的修改后的对象。如何在 beforeReplacement 中有效地替换此更改的对象,以便生成的对象类似于 var afterReplacement

1 个答案:

答案 0 :(得分:1)

var afterReplacement = beforeReplacement.map(function (af) {
    for(var i in changed) {
        if (changed[i].id != af.id) continue; 

        af = changed[i];
        break;
    }
    return af;
});