'How to grouped values in object?
I wrote a function that allows you to group values in an object, but it doesn't work quite right
This is my varation
const response = Object.values(
footerMenu.reduce((acc, key) => {
const { databaseId, parentDatabaseId } = key;
acc[parentDatabaseId] = (acc[parentDatabaseId] || []).concat(key);
return acc;
}, {})
);
example data:
[{parentDatabase: 0, databaseId: 5728}, {parentDatabseId: 5728, databaseId: 5762}....{parentDatabse: 0, databaseId: 4532}, {parentDatabaseId: 4532, databaseId: 3221} ...]
how to group an item so that parent Database Id == 0 has its own items that relate to it
Solution 1:[1]
you have to perform a simple manipulation with the array — group the items by parentDatabaseId
The usual way is by invoking the array.reduce() method with the right callback function:
let array=[{parentDatabase: 0, databaseId: 5728}, {parentDatabase: 5728, databaseId: 5762},{parentDatabase: 0, databaseId: 4532}, {parentDatabase: 4532, databaseId: 3221} ]
const groupByDbId = array.reduce((group, item) => {
const { parentDatabase } = item;
group[parentDatabase] = group[parentDatabase] ?? [];
group[parentDatabase].push(item);
return group;
}, {});
console.log(JSON.stringify(groupByDbId, null, 2));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nermineslimane |
