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

How do I add array items to object properties

本文关键字:对象 属性 添加 数组      更新时间:2023-09-26

我想做以下事情:

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

那么诀窍是什么

谨致问候,bodo

试试这个:

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