我想做以下事情:
// 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)。
那么诀窍是什么?
此致 伯度
答案 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));