javascript - 将对象数组添加到单个数组中

标签 javascript html arrays angularjs object

我正在尝试将对象数组从现有对象推送到新数组。但只有最后一个值被推送

例如:我没有得到 1 2 3 作为输出,而是得到了 3 3 3

var arr=[{'id':'1','name':'xyz'},{'id':'2','name':'pqr'},{'id':'3','name':'mon'}];
var toSend=[];
var obj={'id':""};
for(var i=0;i<arr.length;i++) {
    obj.id = arr[i].id;
  toSend.push(obj);
}

Fiddle link

最佳答案

您将相同的对象引用推送到数组。通过使用新对象,所有对象都不同。

var arr = [{ id: '1', name: 'xyz' }, { id: '2', name: 'pqr' }, { id:'3', name: 'mon' }],
    toSend = [],
    obj;

for (var i = 0; i < arr.length; i++) {
    obj = { id: arr[i].id };
    toSend.push(obj);
}

console.log(toSend);

关于javascript - 将对象数组添加到单个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906577/

相关文章:

javascript - Momentis (PLM) 的 Photoshop 脚本

javascript - Navgoco 不是影响密码保护页面的功能

c# - 从字节数组启动 C# 控制台应用程序

javascript - 对象行为不被理解

c++ - 如何将数组作为参数传递?

javascript - 通过选中复选框切换禁用字段集

javascript - 更改可拖动属性

javascript - highcharts 圆环图中心文本与工具提示重叠

html - 如何在 Bootstrap 缩略图列表中创建 Bootstrap 列

javascript - 使用 find 在容器内进行 jQuery 搜索失去了对 jQuery 的控制