如何将数组项添加到对象属性

时间:2012-09-14 12:26:30

标签: javascript arrays object for-loop

我想做以下事情:

// 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)。

那么诀窍是什么?

此致 伯度

1 个答案:

答案 0 :(得分: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/