繁体   English   中英

如何在对象数组中动态添加 object 值

[英]How to add object value dynamically in array of objects

这是我的 object 数组:

let a = [
    {"team_id": 14, "name": "Aus"},
    {"team_id":39,"name": "New"},
    {"team_id": 44, "name": "Ind",}
]

let b = [{"team_id":39,"name": "New"}]

我想找到 object b值的数组并将新的键值添加到 object "selected":true我想要 output 像这样:

let c = [
    {"team_id": 14, "name": "Aus"},
    {"team_id":39,"name": "New","selected":true},
    {"team_id": 44, "name": "Ind",}
] 

 let a = [{ "team_id": 14, "name": "Aus" }, { "team_id": 39, "name": "New" }, { "team_id": 44, "name": "Ind", }]; let b = [{ "team_id": 39, "name": "New" }]; const result = a.map(rec => { const isPresent = b.find(val => val.team_id === rec.team_id); if (isPresent) { rec.selected = true; } return rec; }); console.log(result)

这是循环遍历第一个数组并查找当前项是否作为第二个数组中的匹配器的代码如果是的话它将返回另一个 object, selected键将添加到其中。

 let a = [ {"team_id": 14, "name": "Aus"}, {"team_id":39,"name": "New"}, {"team_id": 44, "name": "Ind",} ] let b = [{"team_id":39,"name": "New"}] const results = a.reduce((acc, current) => { let exists = b.find(item => item.team_id === current.team_id); return exists? acc.concat({...current, selected: true}): acc.concat(current); }, []); console.log(results);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM