Issue
I have an array of objects which i receive from a db:
[{
key: 'PRODUCT',
item_key: 'ITEM_01',
sequence: 1
},
{
key: 'STORE',
item_key: 'STORE_01',
sequence: 2
}
]
I want to create a Map from it but the condition is, i want the item_key
to be the map key, and only the corresponding array element which matches the item_key
will be the value of that map key. So the map looks like
{
'ITEM_01' => [{
key: 'PRODUCT',
item_key: 'ITEM_01',
sequence: 1
}],
'STORE_01' => [{
key: 'STORE',
item_key: 'STORE_01',
sequence: 2
}]
}
I've kept the value of map keys as an array because there can be more values matching the map key in future. How can i do this?
P.S. by Map
i don't mean the array function map
, but the JS/TS Map
Solution
Use reduce to create an object, if the key exists in the object then push to the array, otherwise create an array and push the item:
const items = [{
key: 'PRODUCT',
item_key: 'ITEM_01',
sequence: 1
},
{
key: 'STORE',
item_key: 'STORE_01',
sequence: 2
}
]
const result = items.reduce((obj, item) => {
if (!obj.hasOwnProperty(item.item_key)) {
obj[item.item_key] = [];
}
obj[item.item_key].push(item);
return obj;
}, {});
console.log(result);
Here is an exmaple with Map:
const map = new Map();
const items = [{
key: 'PRODUCT',
item_key: 'ITEM_01',
sequence: 1
},
{
key: 'STORE',
item_key: 'STORE_01',
sequence: 2
}
]
items.forEach(item => {
if (map.has(item.item_key)) {
map.get(item.item_key).push(item);
} else {
map.set(item.item_key, [item])
}
});
console.log(Object.fromEntries(map))
Answered By - Enve
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.