I have the below logic, my current implementation works fine the last puzzle missing is the parent it, I want to able to assign the same parent id to every similar set of items the current implementation sets the same grandParentId to all items instead to the related collection, in other works items fall under a1 must have the same grandParent and under b2 a different grandParent, I am using uuid library to populate ids.
// arr
let crossCheckArr = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}, {name: 'e'}]
// Object
const rawObj= {
a1: [
{ name: 'a' },
{ name: 'b' },
{ name: 'c' },
],
b2: [{ name: 'd'}],
d3: [{ name: 'e'}],
};
// Consolidation Logic
const grandParentId = uuidv4();
const final = Object.entries(days).reduce((obj, [key, value], i) => {
const parentId = uuidv4();
return {
...obj,
[key]: crossCheckArr.filter((el) => {
if (value.map((name) => name.name).includes(el.name)) {
return Object.assign(el, {
id: uuidv4(),
parentId: parentId,
grandParentId: grandParentId,
});
}
}),
};
}, {});
// Final
// {
// a1: [
// { name: 'a' , parentId : 11, grandParentId : 123},
// { name: 'b', parentId : 11, grandParentId : 123},
// { name: 'c', parentId : 11, grandParentId : 123},
// ],
// b2: [{ name: 'd',parentId : 22, grandParentId : 456}],
// d3: [{ name: 'e',parentId : 33, grandParentId : 789}],
// };