如何在对象中添加另一个嵌套在数组中的项目?

时间:2020-10-22 09:44:39

标签: javascript arrays reactjs object

例如:

track: [
        {
          date: "Date",
          delivered: 0,
          failure: 0,
          in_transit: 0,
          out_for_delivery: 0,
          partially_fulfilled: 0,
          ready_for_pickup: 0,
        },
      ],

在此数组中,在运行时我必须对其进行编辑

track: [
        {
          date: "Date",
          delivered: 0,
          failure: 0,
          in_transit: 0,
          out_for_delivery: 0,
          partially_fulfilled: 0,
          ready_for_pickup: 0,
          unshipped:0,
        },
      ],

我该如何编辑未装运的对象的最后一件东西,我需要告诉大家这不是数组中的一个对象,所以如何动态地将未装运的对象添加到此数组中的每个对象?

2 个答案:

答案 0 :(得分:0)

const arr = [
  {
    date: 'Date',
    delivered: 0,
    failure: 0,
    in_transit: 0,
    out_for_delivery: 0,
    partially_fulfilled: 0,
    ready_for_pickup: 0,
  },
];

arr.forEach((el) => {
  // if(condition){}
  el.unshipped = 0;
});

或者,如果您想添加多个属性,请使用:Object.assign(el, {unshipped: 0})以提高可读性。

答案 1 :(得分:0)

使用forEach

const track = [{
  date: "Date",
  delivered: 0,
  failure: 0,
  in_transit: 0,
  out_for_delivery: 0,
  partially_fulfilled: 0,
  ready_for_pickup: 0,
}]

track.forEach(oTrack => {
  oTrack.unshipped = 0;
});

console.log(track);