![](/img/trans.png)
[英]How to replace key/value pairs in an object of two arrays of objects
[英]A lookup function to match the same IDs in two different arrays of objects and inserting key/value pairs into one of the array of objects
我有 2 个不同的 arrays 和对象。 我想基本上匹配两个对象数组的 ID,然后基本上从匹配的 object 中获取键值对并将其添加到另一个数组的 object 中。
例如,这是对象数组之一
const groups = [{id: "1234"}, {id: "4321}]
第二个数组看起来像这样
const childCategories = [{id: "4321", url:"/b/test"}, {id: "2223", url:"/b/test32"}]
因此,在这种情况下,由于childCategories.id = "4321"
与 groups.id = groups.id = "4321"
4321" 匹配,它会将url: "/b/test"
添加到组 object 的匹配 ID 中,因此结果应该是
const groups = [{id: "4321", url: "/b/test"}, {id: "1234}]
它还应该只将url
键值对添加到groups
object 中,因为可能有其他属性不应添加到groups
object 中。
我曾尝试使用.find
,但我认为 IE11 不支持它。
这是目前我目前尝试过的,它不是很正常,或者可能是最有效的。
const getCategoryUrl = (childCategories, groups) => {
groups.map(group => {
const url = childCategories.find(child => child.id === group.id).url;
childCategories.find(child => child.id === group.id) ? {...group, url} : group
})
return groups
}
你可以这样做,没有找到:
childCategories.forEach(cc => {
groups.forEach(g =>{
if(cc.id == g.id){
g.url = cc.url;
}
});
我应该指出,这是非常低效的,因为它为 childCategories 中的每个 object 完全遍历组集合。
使用 find 它看起来像这样:
childCategories.forEach(cc => {
let matchGroup = groups.find(g =>{
return g.id == cc.id;
});
if(matchGroup!=null) matchGroup.url = cc.url;
});
它是否能够让它与它一起工作
const getCategory = (childCategories, groups) => {
let matchGroup;
groups.map(group => {
matchGroup = childCategories.filter(child =>
child.id === group.id ? {...group,url: child.url} : group
)
})
return matchGroup
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.