joy08
joy08

Reputation: 9652

Want to add an array of objects inside a nested object: Javascript

I need to add an array of objects to another object whose structure has been shown below.

Here arr is the array of objects that needs to be added to "dest" object.

Help would be appreciated.

Structure:


var arr = [
    { field: "state", value: "value2"},
    { field: "city", value: "value3"}
];
    

This array of objects needs to be added to an object of following structure:


var dest = {
    "topic": "test",
    "filter": {
        "sequence": [
            {
                "field": "country",
                "value": "value1",
            }
        ]
    },
    "order": [
        {
            "field": "field1",
            "order": "backward"
        }
    ]
}


I would want to add the fields of arr inside sequence so that result would be something like this:


var dest = {
    "topic": "test",
    "filter": {
        "sequence": [
            {
                "field": "country",
                "value": "value1",
            },
            {
                "field": "state",
                "value": "value2",
            },
            {
                "field": "city",
                "value": "value3",
            }
        ]
    },
    "order": [
        {
            "field": "field1",
            "order": "backward"
        }
    ]
}

Upvotes: 0

Views: 2055

Answers (2)

MH2K9
MH2K9

Reputation: 12039

Using forEach() you can do it.

var arr = [
    { field: "state", value: "value2"},
    { field: "city", value: "value3"}
];

var dest = {
    "topic": "test",
    "filter": {
        "sequence": [
            {
                "field": "country",
                "value": "value1",
            }
        ]
    },
    "order": [
        {
            "field": "field1",
            "order": "backward"
        }
    ]
}

arr.forEach(function (item) {
    dest.filter.sequence.push(item)
});

console.log(dest)

Also ES6 spread operator can be used to merge

var arr = [
    { field: "state", value: "value2"},
    { field: "city", value: "value3"}
];

var dest = {
    "topic": "test",
    "filter": {
        "sequence": [
            {
                "field": "country",
                "value": "value1",
            }
        ]
    },
    "order": [
        {
            "field": "field1",
            "order": "backward"
        }
    ]
}
    
dest.filter.sequence.push(...arr)

console.log(dest)

Upvotes: 2

Koviri Jagdish
Koviri Jagdish

Reputation: 76

You just need to use below code to insert array into object.

        arr.forEach( function(value, index, array) {
            dest.filter.sequence.push(value);
        });

Upvotes: 0

Related Questions