我有一个格式如下的对象数组:
{
"_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/