我正在尝试将一个对象添加到另一个对象中。
我之前的帖子帮助我解决了数组问题,但我也需要将对象添加到对象中。
我有类似的东西
var temp = {};
for(var i=0; i<test.length; i++){
console.log(test[i])
console.log(product[i])
temp.test[i] =product[i];
}
console.log 都显示值。然而,我得到了
temp.test[i] =product[i]
的“未捕获类型错误:无法设置未定义的属性“0””
有人可以帮我解决这个问题吗?非常感谢
最佳答案
var temp = {test:[], product:[]};
var test = ['a','v'];
var product = ['a2','v2'];
for(var i=0; i<test.length; i++){
console.log(test[i])
console.log(product[i])
temp.test.push(product[i]);
}
您需要先定义您的属性测试和产品,然后再推送数据。
但是,您不必循环插入每个值。您只需一次即可设置整个集合。
var testCollection = ['Value 1', 'Value 2'];
var productCollection = ['Value 10', 'Value 20'];
var temp = {
test:testCollection
, product:productCollection
};
关于javascript - 如何将一个对象添加到一个对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25372935/