[英]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. 这里的arr是需要添加到“目标”对象的对象数组。
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: 我想在“序列”中添加“ arr”字段,以便结果如下所示:
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. 使用
forEach()
可以做到。
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 ES6 传播算子也可以用于合并
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.