admin管理员组文章数量:1200977
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]
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]
Share
Improve this question
edited Jul 14, 2012 at 20:32
pb2q
59.6k19 gold badges149 silver badges152 bronze badges
asked Jul 14, 2012 at 20:22
SamSam
1,1453 gold badges14 silver badges24 bronze badges
7
- 4 This isn't really an array merge as much as it is a combine. – Jason McCreary Commented Jul 14, 2012 at 20:24
- 1 You can do it manually in a simple for loop. – user377628 Commented Jul 14, 2012 at 20:24
- 4 jQuery is not a language. Also, JavaScript doesn't have associative arrays, just objects. – Ry- ♦ Commented Jul 14, 2012 at 20:24
- 1 What would be the point, if you could just reference two corresponding entries based on them sharing the same array index? – Alex W Commented Jul 14, 2012 at 20:26
- 1 @davidethell: That's not the same thing. – Ry- ♦ Commented Jul 14, 2012 at 20:26
5 Answers
Reset to default 12var 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}
here's a working jsFiddle
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];
}
Even easier:
$.merge(arr1, arr2);
本文标签: jqueryCombine two arrays in JavaScriptStack Overflow
版权声明:本文标题:jquery - Combine two arrays in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738622336a2103261.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论