如何在JavaScript中将对象推送到数组对象?

时间:2018-07-19 08:57:18

标签: javascript

如何在JavaScript中将对象推送到数组对象? 我下面有像数据1这样的数据数组对象,我想把下面的像数据2这样的多个数据对象变成数据结果,该怎么做?

数据1:

[ {
    _id: 5b4ef851e1e5b938489cb952,
    name: 'Stanlee',
    data: 2,
    __v: 0 },
  { 
    _id: 5b4ef717e1e5b938489cb94e,
    name: 'Jhone ',
    data: 2,
    __v: 0 },
  { 
    _id: 5b4ee85b81bf2115b8ae0a8d,
    name: 'Sushio',
    data: 2,
    __v: 0 } ]

数据2:

[{ id: 2,
  name: 'transportation',
  type: 'car'},
{ id: 2,
  name: 'transportation',
  type: 'motor'},
{ id: 2,
  name: 'transportation',
  type: 'train'}]

数据结果:

[ {
    _id: 5b4ef851e1e5b938489cb952,
    name: 'Stanlee',
    data: { id: 2,
            name: 'transportation',
            type: 'car'}
    __v: 0 },
  { 
    _id: 5b4ef717e1e5b938489cb94e,
    name: 'Jhone ',
    data: { id: 2,
            name: 'transportation',
            type: 'motor'}
    __v: 0 },
  { 
    _id: 5b4ee85b81bf2115b8ae0a8d,
    name: 'Sushio',
    data: { id: 2,
            name: 'transportation',
            type: 'train'}
    __v: 0 } ]

2 个答案:

答案 0 :(得分:2)

您可以使用data1.forEach((x, i) => x.data = data2[i] || x.data);

在下面尝试:

var data1 = [{
    _id: "5b4ef851e1e5b938489cb952",
    name: 'Stanlee',
    data: 2,
    __v: 0
  },
  {
    _id: "5b4ef717e1e5b938489cb94e",
    name: 'Jhone ',
    data: 2,
    __v: 0
  },
  {
    _id: "5b4ee85b81bf2115b8ae0a8d",
    name: 'Sushio',
    data: 2,
    __v: 0
  }
];

var data2 = [{
    id: 2,
    name: 'transportation',
    type: 'car'
  },
  {
    id: 2,
    name: 'transportation',
    type: 'motor'
  },
  {
    id: 2,
    name: 'transportation',
    type: 'train'
  }
];

data1.forEach((x, i) => x.data = data2[i] || x.data);
console.log(data1);

答案 1 :(得分:0)

var d1=[{a:1},{a:1},{a:3}];
var d2=[{a:4},{a:5}];

document.write("Data 1 : " + JSON.stringify(d1) +"<br/>");

document.write("Data 2 : " + JSON.stringify(d2) +"<br/>");

d2.forEach(function(obj) {
  d1.push(obj);
});

document.write("Data 1 : " + JSON.stringify(d1));