状态不变的循环内的对象更新

时间:2018-07-23 18:34:52

标签: javascript reactjs ecmascript-6

我正在研究React应用程序,我需要在其中更新我的objcet循环, 我的对象结构是

[{
    "iD": "101",
    "bD": "06/02/2018",
    "cD": "16/04/2018"
  },
  {
    "iD": "102",
    "bD": "06/02/2018",
    "cD": "16/04/2018"
  },
  {
    "iD": "103",
    "bD": "06/02/2018",
    "cD": "16/04/2018"
}]

我的想法是我必须为每个对象添加几个键,我采用的方法似乎不合适,因为我正在更新对象,而不是将更新后的值压入数组并返回新值。周围是否还有其他方法可以通过突变来更新它?

我正在尝试for for循环:

let newList = {};
for (let key in list) {
    newList = Object.assign({}, list[key]);
    newList.newKey1 = 'demo1';
    newList.newKey2 = 'demo2';
};

现在,如果我返回newList,它将始终具有最后更新的值。因此,我将如何获取完整的更新列表。数组可能也只有一项:

[{
  "id":"101",
  "bD":"06/02/2018",
  "cD":"16/04/2018"
}]

2 个答案:

答案 0 :(得分:3)

要通过直接突变将数组中的每个项目转换为其他项目,您只需使用for(for..offorEach)循环的版本:

const items = [{
    iD: "101",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "102",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "103",
    bD: "06/02/2018",
    cD: "16/04/2018"
  }
];

for (const item of items) {
  item.newKey1 = 'demo1';
  item.newKey2 = 'demo2';
}

console.log(
  items
);

要通过返回更改了项目的新数组将数组中的每个项目转换为某种内容,应使用Array.prototype.map

const items = [
  {
    iD: "101",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "102",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "103",
    bD: "06/02/2018",
    cD: "16/04/2018"
  }
];

console.log(
  items.map(item =>
    Object.assign({}, item, {
      newKey1: "demo1",
      newKey2: "demo2"
    })
  )
);

或者如果您的环境支持则使用对象散布:

const items = [
  {
    iD: "101",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "102",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "103",
    bD: "06/02/2018",
    cD: "16/04/2018"
  }
];

console.log(
  items.map(item => ({
    ...item,
    newKey1: "demo1",
    newKey2: "demo2"
  }))
);

答案 1 :(得分:0)

我解决了这个问题,并在每次更新的obj中推送了一个数组。

例如

const items = [
  {
    iD: "101",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "102",
    bD: "06/02/2018",
    cD: "16/04/2018"
  },
  {
    iD: "103",
    bD: "06/02/2018",
    cD: "16/04/2018"
  }
];


    let bObj = {};
    let uObj = [];

    for ( const item of items ) {
      bObj = Object.assign({}, item )
      bObj.newKey1 = 'Test1';
      bObj.newKey2 = 'Test2';
      uObj.push(bObj);
   }
   return uObj;