I currently have 2 different arrays of objects
const arr1 = [
{
groupId: "Category",
options: [
{name: "cookies", id: 1111},
{name: "tv", id: 2222}
]
},
{
groupId: "Brand",
options: [
{name: "test1", id: 2222}
]
},
{
groupId: "Price",
options: [
{name: "test2", id: 4444}
]
}
]
const arr2 = [
{
id: 1111,
url: "/test"
},
{
id: 2222,
url: "/test1"
},
{
id: 3333,
url: "/test2
}
]
How would I merge arr2's object into arr1's object based on the matching obj ids? So for example the expected should be
const result = [
{
groupId: "Category",
options: [
{name: "cookies", id: 1111, url: "/test"},
{name: "tv", id: 2222, url: "/test1"}
]
},
{
groupId: "Brand",
options: [
{name: "test1", id: 2222, url: "/test1"}
]
},
{
groupId: "Price",
options: [
{name: "test2", id: 4444}
]
}
]
This is what I currently have but I can't seem to get it to give me the expected result.
const getNewArr = (arr2, arr1) => {
const categoryGroup = arr1.find(group => group.groupId === "Category");
if (categoryGroup) {
let matchGroup;
categoryGroup.options.map(group => {
matchGroup = arr2.filter(child =>
child.categoryId === group.id ? {...group, child} : group
);
});
return {...categoryGroup.options,...matchGroup};
}
return arr1;
}
I tried a few things but I am unable to get it working so far. Am I missing something or is there something else that needs to be done?