[英]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
I have 2 different arrays with objects.我有 2 个不同的 arrays 和对象。 I want to be basically match an ID from both of the array of objects and then basically take the key value pair from the matching object and add it to the other array's object.我想基本上匹配两个对象数组的 ID,然后基本上从匹配的 object 中获取键值对并将其添加到另一个数组的 object 中。
For example this is one of the array of objects例如,这是对象数组之一
const groups = [{id: "1234"}, {id: "4321}]
The second array would look something like this第二个数组看起来像这样
const childCategories = [{id: "4321", url:"/b/test"}, {id: "2223", url:"/b/test32"}]
So in this case since childCategories.id = "4321"
matches with groups.id = "4321"
it would add the url: "/b/test"
to the matching ID's to the groups object so the result should be因此,在这种情况下,由于childCategories.id = "4321"
与 groups.id = groups.id = "4321"
4321" 匹配,它会将url: "/b/test"
添加到组 object 的匹配 ID 中,因此结果应该是
const groups = [{id: "4321", url: "/b/test"}, {id: "1234}]
It should also only add the url
key value pair to the groups
object as there can be other properties that shouldn't be added to the groups
object.它还应该只将url
键值对添加到groups
object 中,因为可能有其他属性不应添加到groups
object 中。
I have tried using .find
but i don't think it's supported by IE11.我曾尝试使用.find
,但我认为 IE11 不支持它。
This is currently what I've currently tried and it's not quite working properly or probably the most efficient.这是目前我目前尝试过的,它不是很正常,或者可能是最有效的。
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
}
You could do it like this, without a find:你可以这样做,没有找到:
childCategories.forEach(cc => {
groups.forEach(g =>{
if(cc.id == g.id){
g.url = cc.url;
}
});
This is, I should point out, pretty horribly inefficient, as it iterates through the groups collection completely for every object in childCategories.我应该指出,这是非常低效的,因为它为 childCategories 中的每个 object 完全遍历组集合。
With find it would look something like this:使用 find 它看起来像这样:
childCategories.forEach(cc => {
let matchGroup = groups.find(g =>{
return g.id == cc.id;
});
if(matchGroup!=null) matchGroup.url = cc.url;
});
Was it able to get it working with this它是否能够让它与它一起工作
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.