I have 2 different arrays with objects. 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.
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
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.
I have tried using .find
but i don’t think it’s supported by 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 }
Advertisement
Answer
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 }