如果id匹配,如何将对象中的值替换为对象中的另一个更新值?



目前,我将类型存储在reducer中。

const genre = {
"0": {
"id": 1912,
"title": "Fiction",
"name": "Greg"
},
"1": {
"id": 1957,
"title": "Non-Fiction",
"name": "John"
},
"2": {
"id": 1958,
"title": "Literature",
"name": "James"
},
}

如何检查updatedGenre中的id匹配类型中的id,然后我将更新标题或名称更新后的标题或名称基于id。

const updatedGenre = {
"id": 1958,
"title": "Literature & Poems",
"name": "Leo"
}

输出示例:(示例id: 1958)

const genre = {
"0": {
"id": 1912,
"title": "Fiction",
"name": "Greg"
},
"1": {
"id": 1957,
"title": "Non-Fiction",
"name": "John"
},
"2": {
"id": 1958,
"title": "Literature & Poems",
"name": "Leo"
},
}

您应该能够通过对象的迭代来完成此操作。见下文:

for (const key in genre) {
if (genre[key]["id"] === updatedGenre["id"]) { 
genre[key]["title"] = updatedGenre["title"] 
}
}

让我知道它是否有效,祝你好运!

最新更新