簡體   English   中英

如何使用數組過濾器在數組內的對象內查找值,然后更改/編輯該值?

[英]How can I use array filter to find value of value inside an object inside an array and then change/edit that value?

說我有這樣的事情:

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,如下所示: var = 2

如何在函數內的諸如“數組過濾器()”之類的東西中使用該變量(在這種情況下對更簡單的數組方法實現開放),以便我可以“提取” todos:整個對象todos:包含 id 值的數組在上面的示例中,它與我的 var 值相同(在此示例中id:2 ),然后還修改/編輯該特定對象的text:值(在此示例中為 this.state.text),同時還確保對象作為一個整體將留在與以前相同的位置? (這可以通過 id/var 的值來引用,因為它與我的索引方式相對應)。

換句話說,如何編輯對象的文本值,該對象的 id 與我的 var 值相同?

有人告訴我,這可以通過數組過濾器方法實現,但我很難看出這是怎么可能的。 此外,我是一個菜鳥,所以...不過真的很重視學習機會! 先感謝您。

您不需要函數array.prototype.filter ,而是使用函數Array.prototype.find根據執行條件的測試函數查找對象。

函數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; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM