gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:22:09 26 4
gpt4 key购买 nike

我想要执行以下操作:

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

关于javascript - 如何将数组项添加到对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12424552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com