javascript - 更新数组中对象的更干净的方法

标签 javascript arrays reactjs javascript-objects dom-events

我有一个格式如下的对象数组:

{
  "_id": "590cbcd9bf2b9b18ab3c3112",
  "title": "",
  "content": "Create Notes Webapp",
  "checked": true,
  "listID": "590cbc61bf2b9b18ab3c3110"
},
{
  "_id": "590cfe5a86fe0908c560c2b0",
  "title": "A Note 01",
  "content": "My first note.",
  "checked": false,
  "listID": "590cbe15bf2b9b18ab3c3114"
}

这是我必须更新每个项目的代码:

  onTextChange = (key, note, value) => {
    clearTimeout(timeoutID);
    switch (key) {
      default:
        break;
      case 'title':
        note.title = value;
        break;
      case 'checked':
        note.checked = value;
        break;
      case 'content':
        note.content = value;
        break;
    }
    var notes = this.state.notes;
    var id;
    for (var i in notes) {
      if (notes[i]._id === note._id) {
        notes[i] = note;
        id = i;
        break;
      }
    }
    this.setState({ notes }, () => { timeoutID = setTimeout(() => this.updateNote(this.state.notes[id]), 3000); });

  }

这被称为这样:

onChange={(e, value) => this.onTextChange('title', note, value)}

有没有比使用 switch 语句更好的方法来更新对象中的指定项?另外,是否有比 for 循环更简单的扫描数组查找 id 的方法?

最佳答案

有没有比使用 switch 语句更好的方法来更新对象中的指定项?

您可以使用此语法来更新注释对象。这也确保它不会将新属性插入注释中。

if (note.hasOwnProperty(key) {
  note[key] = value
}

要使用更清晰的语法来更新注释,您可以这样做

var newNotes = this.state.notes.map(n => n._id === note._id ? note : n);
this.setState({notes: newNotes});

这将创建一个 newNotes 数组,该数组与当前状态相同,只是它将替换传入的 ._id 等于数组中的数组。

您还必须调整 updateNote 调用,因为您不再保存索引,但您可能只使用 note 变量?

关于javascript - 更新数组中对象的更干净的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43814833/

相关文章:

循环内的Javascript函数不适用于其他div

javascript - 如何取消Meteor.setTimeout?

javascript - 任何 Sublime Text 插件都可以使用匿名函数自动包装生成的 js

javascript - 在函数调用时将数组解析为字符串

javascript - 外部 js 仅在刷新后加载到 react 组件中

reactjs - 防止事件监听器多次触发

javascript - 删除由缩放引起的谷歌地图上的网格线

C++ : Turn char array into a string that is printed

arrays - oracle pl/sql 数组

javascript - React HashRouter不渲染其他路径,仅渲染根组件 '/'