我正在尝试将一个对象添加到我的数组中,但是当我访问它时它只显示 [object Object]
我有几个对象数组,我想将它们链接到一个对象数组中。
我已经尝试过 .concat() 和 .push ,但不幸的是总是得到相同的答案。
重要的是要注意 response
是来自服务器的响应,所以它每次都会改变,因此需要将它们连接到一个“最终”数组中
当我调用 console.log(response[x])
时,我得到了预期的结果
{
Name : John,
surname : doe,
Age : 30,
face : Object {
eyes : brown,
hair : dark
}
}
但是当我将它分配给 res 时,我得到了 [object Object]
代码如下:
res = [];
response = [{Name:John, surname:doe, Age: 30, face: Object{eyes:brown, hair:dark}},{Name:Jane, surname:doe, Age: 35, face: Object{eyes:blue, hair:blond}];
for(var x = 0; x < response.length; x++ ){
//push individual object to the etnire response "res" array
res[x] = response[x];
//res.push(response[x])
//res = res.concat(response) (getting rid of the surrounding array of course)
console.log("res = " + res[x]);
//console.log(response[x])
}
我希望将每个数组的副本放入“最终”数组中,因此对于此示例,它将是:
res
等于 [{Name:John, surname:doe, Age: 30, face: Object{eyes:brown, hair:dark}},{Name:Jane, surname:doe,年龄:35,脸:对象{眼睛:蓝色,头发:金发}]
每个新对象都会添加到现有数组中。
最佳答案
当您将 object 转换为 string 时,错误使用了控制台日志。
试试 console.log("res = ", res[x]);
关于javascript - 连接对象数组混淆了对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53888093/