我有动态数量的属性对象和包含动态数量项的数组。我需要迭代它们并将数组的值赋给object的属性。
var obj = {
property1: null,
property2: null,
.....
};
var array = ["some value1", "some value2"...];
必须
var obj = {
property1: "some value1",
property2: "some value2",
.....
}
答案 0 :(得分:0)
如果字面上有property1
等,那么它非常简单,因为我们可以使用数组索引和括号表示法来构建该索引的属性名称(加一) :
var obj = {
property1: null,
property2: null
//.....
};
var array = ["some value1", "some value2"/*...*/];
array.forEach(function(value, index) {
// vvvvvvvvvvvvvvvvvvvvvvvv------ string concat to build the property name
obj["property" + (index + 1)] = value;
// ^------------------------^----- brackets notation to refer to the property
// using a runtime-defined name
});
console.log(obj);
答案 1 :(得分:0)
这是我的答案。 如果动态属性的名称,那么,
var obj = {
property1: null,
property2: null,
};
var array = ["some value1", "some value2"];
var i=0
for (var index in obj) {
if (obj.hasOwnProperty(index)) {
obj[index]=array[i];
}
i++;
}
console.log(obj);