簡體   English   中英

JAVASCRIPT:更改對象 ID 匹配的對象列表中的密鑰對

[英]JAVASCRIPT: Change the key pair in a list of objects where the object ID matches

我有一個對象如下

{
  "id":34567,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"The description goes here",
  "favorite":false,
}

我的問題是,只有在 id = 34567 的情況下才需要什么 JavaScript 才能更改“最喜歡的”值

所以結果會變成 ;

{
  "id":34567,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"The description goes here",
  "favorite":true,
}

您可以將其從數組中過濾掉,並更改過濾元素數組的第一個元素的鍵值。 像這兒:

 const data = [{ "id":34567, "description":"The description goes here", "favorite":false, }, { "id":34569, "description":"The description goes here", "favorite":false, }]; console.log(data); const addFavorite = (id) => { data.filter((d) => d.id==id)[0].favorite = true; } addFavorite(34569); console.log(data);

或者,如果 ID 是唯一的,您可以使用 find 方法,如
@cmgchess 在下面的評論部分中提到。

 const data = [{ "id":34567, "description":"The description goes here", "favorite":false, }, { "id":34569, "description":"The description goes here", "favorite":false, }]; console.log(data); const addFavorite = (id) => { data.find((d) => d.id==id).favorite = true; } addFavorite(34569); console.log(data);

如果 ID 不是唯一的,您可以映射所有過濾的元素。

 const data = [{ "id":34567, "description":"The description goes here", "favorite":false, }, { "id":34569, "description":"The description goes here", "favorite":false, }, { "id":34569, "description":"It is a copy", "favorite":false, } ]; console.log(data); const toggleFavorite = (id) => { data.filter((d) => d.id==id).map((d)=>d.favorite = !d.favorite); } toggleFavorite(34569); console.log(data);

您可以為此使用地圖功能。

data = data.map(d => {
    if(d.id === 34569) {
        d.favorite = true;
    }
    return d;
});

如果數組中有多個滿足條件的對象,這也將起作用。

暫無
暫無

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

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