[英]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.