0

我想做以下事情:

// an object
var object = {
    one: null,
    two: null,
    three: null
};

// an array
var array = ['this is one', 'this is two', 'this is three'];

我现在想将它们合并在一起,所以我得到了;

var merged = {
    one: 'this is one',
    two: 'this is two',
    three: 'this is three'
};

我不想只使用纯 javascript (ECMA5) 的任何第三个库。

那么诀窍是什么?

问候,博多

4

1 回答 1

2

尝试这个:

// an object 
var object = {
    one: null,
    two: null,
    three: null
};

// an array 
var array = ['this is one', 'this is two', 'this is three'];

function merge(arraysrc, array2dest) {

    var x, i = 0;

    var merged = [];

    for (x in array2dest) {
        var obj = {};
        obj[x] = arraysrc[i++];
        merged.push(obj);
    }
    return merged;
}

var a = merge(array, object);

alert(JSON.stringify(a));​

http://jsfiddle.net/6mQYN/

于 2012-09-14T14:00:06.977 回答