[英]JAVASCRIPT: Change the key pair in a list of objects where the object ID matches
I have an object as follows我有一个对象如下
{
"id":34567,
"description":"The description goes here",
"favorite":false,
},
{
"id":34569,
"description":"The description goes here",
"favorite":false,
}
My question is, what JavaScript is required to change the 'favorite' value ONLY where the id = 34567我的问题是,只有在 id = 34567 的情况下才需要什么 JavaScript 才能更改“最喜欢的”值
So the result will become ;所以结果会变成 ;
{
"id":34567,
"description":"The description goes here",
"favorite":false,
},
{
"id":34569,
"description":"The description goes here",
"favorite":true,
}
You can filter it out from the array, and change the keys value of the first elemnt of the array of filtered elements.您可以将其从数组中过滤掉,并更改过滤元素数组的第一个元素的键值。 Like here:
像这儿:
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);
Or you can use the find method if tha ID's are unique, as或者,如果 ID 是唯一的,您可以使用 find 方法,如
@cmgchess mentioned below in the comments section. @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);
And you can map through all the filtered elements if the ID isn't unique.如果 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);
you can use map function for this.您可以为此使用地图功能。
data = data.map(d => {
if(d.id === 34569) {
d.favorite = true;
}
return d;
});
this will also work if there are multiple objects in array which satisfy the condition.如果数组中有多个满足条件的对象,这也将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.