forgottofly
forgottofly

Reputation: 2719

Replace the JSON object after updating using javascript

This is a follow up quesstion for JSON replacement where I was not able to get a proper response. Hence I'm posting this question with a better example.

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"
                }
            ]
        }
    ]

I have changed the name in var beforeReplacement and have mentioned the modified object that I will be receiving after the changes. How can I efficiently replace this changed object in the beforeReplacement so that the resultant object will be like var afterReplacement

Upvotes: 0

Views: 105

Answers (1)

kmhigashioka
kmhigashioka

Reputation: 521

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

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

Upvotes: 1

Related Questions