Can I merge two arrays in JavaScript like this?
these arrays:
arr1 = ['one','two','three'];
arr2 = [1,2,3];
into
arr3 = ['one': 1, 'two': 2, 'three' : 3]
var arr3 = {};
for (var i = 0; i < arr1.length; i++) {
arr3[arr1[i]] = arr2[i];
}
Please note that arr3
is not array, it is object .
You can use Array.prototype.reduce
...
var arr3 = arr1.reduce(function(obj, val, i) {
obj[val] = arr2[i];
return obj;
}, {});
DEMO: http://jsfiddle.net/GMxcM/
{
"one": 1,
"two": 2,
"three": 3
}
Just because you said in jQuery
, here's a jQuery $.each
version.
arr1 = ['one','two','three'];
arr2 = [1,2,3];
arr3 = {};
$.each(arr1, function(i, value){
arr3[value] = arr2[i];
});
console.log(JSON.stringify(arr3));
output ->
{"one":1,"two":2,"three":3}
Loop!
var arr1 = ['one','two','three'];
var arr2 = [1,2,3];
var result = {};
for(var i = 0; i < arr1.length; i++) {
result[arr1[i]] = arr2[i];
}
更简单:
$.merge(arr1, arr2);
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.