说我有这样的东西:
this.state = {
todos: [{id:0, text:this.state.text, isEdit: this.state.isEdit, priority: this.state.priority}, {id:1, text:this.state.text, isEdit: this.state.isEdit, priority: this.state.priority}, {id:2, text:this.state.text, isEdit: this.state.isEdit, priority: this.state.priority}]
};
我有一个等于2的变量,像这样:var = 2
如何在函数中 使用 在诸如“ Array filter()”(此情况下更容易实现数组方法实现)之类的变量中使用该变量,可以在上面示例中包含ID值的todos:
数组中“提取” 整个 对象,即 相同值作为我的var (在此示例中为id:2
),然后然后修改/编辑该特定对象的text:
值(this.state。文本,在此示例中),同时还确保将整个对象保留在与以前相同的位置? (这可以通过id / var的值来引用,因为它与我索引的方式相对应。)
换句话说,我该如何 编辑 对象的文本值,该对象的id与我们的var值相同?
有人告诉我,使用数组过滤器方法可以做到这一点,但是我很难知道如何做到这一点。我也是菜鸟,所以……真的很珍惜学习机会!预先谢谢你。
答案 0 :(得分:1)
您不需要功能array.prototype.filter
,而可以使用功能Array.prototype.find
根据执行条件的测试功能来查找对象。
满足提供的测试功能的数组中的第一个元素的值;否则,将返回undefined。
let state = { todos: [{ id: 0, text: "text", isEdit: true, priority: 3 }, { id: 1, text: "text1", isEdit: false, priority: 3 }, { id: 2, text: "text2", isEdit: true, priority: 2 }]},
id = 2,
found = state.todos.find(o => o.id === id);
if (found) found.text = "NewText2";
console.log(state);
.as-console-wrapper { max-height: 100% !important; top: 0; }