我的输入如下。它是一个对象数组,每个对象都有状态,这也是一个对象数组。我想追加details
当状态 id 与状态匹配时,在 states 对象内部id
如以下所说的。 IE。82175746
const input =
[
{
"country": { "id": 87745195, "action": "Analyze" },
"states": [
{ "id": 83589582, "action": "Verify" },
{ "id": 87335656, "action": "Analyze" }
]
},
{
"country": { "id": 83861166, "action": "Verify" },
"states": [
{ "id": 82175746, "action": "Closed" },
{ "id": 78745158, "action": "Closed" }
]
}
]
const details = { "totalOpenRadars": 1, "totalClosedRadars": 1 }
const id = 82175746
这就是我想要达到的结果。请注意,ID 82175746 会与所有州 ID 进行比较。一旦找到匹配项,上述详细信息就会如下所示附加到匹配的对象中。
const result =
[
{
"country": { "id": 87745195, "action": "Analyze" },
"states": [
{ "id": 83589582, "action": "Verify" },
{ "id": 87335656, "action": "Analyze" }
]
},
{
"country": { "id": 83861166, "action": "Verify" },
"states": [
{ "id": 82175746, "action": "Closed", "details": { "totalOpenRadars": 1, "totalClosedRadars": 1 } },
{ "id": 78745158, "action": "Closed" }
]
}
]
为了实现这一目标,我尝试了这种方法,但无法正确获得结果。
有人可以告诉我哪里出了问题吗
const result = input.forEach((element) => {
element.states.forEach((state) => {
if(state.id === id) {
state.details = details
}
});
});