[英]How to merge 2 javaScript Array?
I have 2 Arrays.我有 2 个数组。
I want to merge the Field Values from 2nd Array with the 1st Array.我想将第二个数组中的字段值与第一个数组合并。
Every value (ie "Test") belongs to the Profile Field id listed in the _embedded part of 2nd Array (_embedded.profileField.id).每个值(即“测试”)都属于第二个数组 (_embedded.profileField.id) 的 _embedded 部分中列出的配置文件字段 ID。
0: Object
field: "FieldLabel1"
id: 1
1: Object
field: "FieldLabel2"
id: 7
2: Object
field: "FieldLabel3"
id: 12
0: Object
id: 1
value: "Test"
_embedded: Object
profileField: Object
field: "FieldLabel1"
id: 1
1: Object
id: 2
value: "links"
_embedded: Object
profileField: Object
field: "FieldLabel2"
id: 7
How can I get one Array with both informations together?我怎样才能得到一个同时包含这两个信息的数组?
Using map
and filter
from Array methods U can merge this arrays with condition you need.使用Array 方法中的
map
和filter
可以将这些数组与您需要的条件合并。 Please see following examples:请参阅以下示例:
/* your arrays definition */
var a = [{
field: "FieldLabel1",
id: 1
}, {
field: "FieldLabel2",
id: 7
}, {
field: "FieldLabel3",
id: 12
}
];
var b = [{
id: 1,
value: "Test",
_embedded: {
profileField: {
field: "FieldLabel1",
id: 1
}
}
}, {
id: 2,
value: "links",
_embedded: {
profileField: {
field: "FieldLabel2",
id: 7
}
}
}];
/* mergedArray contains merged data from two arrays arranged by id */
var mergedArray = a.map(function(aItem){
var value = b.filter(function(bItem) {
return aItem.id === bItem._embedded.profileField.id;
}).map(function(item){
return item.value;
}).pop();
aItem.value = value;
return aItem;
});
the result is:结果是:
margedArray: Array[3]
0: Object
field: "FieldLabel1"
id: 1
value: "Test"
1: Object
field: "FieldLabel2"
id: 7
value: "links"
2: Object
field: "FieldLabel3"
id: 12
value: undefined
Hi Simply use Jquery see below code!嗨,只需使用 Jquery,请参阅下面的代码!
For Array:对于数组:
var newArray = $.merge(1Array, 2Array);
For Object:对于对象:
var object = $.extend({}, object1, object2);
For array: jquery merge array对于数组: jquery 合并数组
For Object: jquery merge object对于对象: jquery 合并对象
Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.