简体   繁体   中英

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

I need to add an array of objects to an 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 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 add the fields of "arr" inside "sequence" so that result would 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"
                  }
            ]
}


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) 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM