簡體   English   中英

如何將數組項添加到對象屬性

[英]How do I add array items to object properties

我想做以下事情:

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

那訣竅是什么?

此致,博多

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM