最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to merge two arrays as keyval - Stack Overflow

programmeradmin3浏览0评论

How can you merge two arrays into key/value pairs please?

From this...

array1 = ['test1', 'test2'];
array2 = ['1', '2'];

To this...

array3 = ['test1':'1', 'test2':'2'];

How can you merge two arrays into key/value pairs please?

From this...

array1 = ['test1', 'test2'];
array2 = ['1', '2'];

To this...

array3 = ['test1':'1', 'test2':'2'];
Share Improve this question edited Oct 27, 2011 at 13:59 Alex asked Oct 27, 2011 at 13:48 AlexAlex 1812 silver badges9 bronze badges 2
  • 2 The syntax of array3 you provided isn't "key-value" syntax. – duri Commented Oct 27, 2011 at 13:51
  • 1 I think for your result you mean array3 = {'test1':'1', 'test2':'2'};, don't you? If so, then the answer with the phpjs array_bine will do just fine. – Jonathan M Commented Oct 27, 2011 at 13:53
Add a ment  | 

2 Answers 2

Reset to default 5

If you are using underscore.js http://documentcloud.github./underscore/#zip you can simply do:

var zipped = _.zip(array1,array2);
_(zipped).map(function(v){ return v[0] + ":" + v[1] });

See http://phpjs/functions/array_bine:307

EDIT: Looking at your question again, you might be after something more like this:

function mergeArrays(arr1, arr2) {
    var l = Math.min(arr1.length,arr2.length),
            ret = [],
            i;

    for( i=0; i<l; i++) {
       ret.push(arr1[i]+":"+arr2[i]);
    }

    return ret;
}
发布评论

评论列表(0)

  1. 暂无评论