I am trying to get all the items in a flat dataset that are grouped together to form a hierarchical dataset using Javascript/Node.JS.
I have a solution, but I don't think it's the most elegant and it could probably be improved.
I based my solution of the answer here Find all objects with matching Ids javascript
My dataset is as follows:
let data = [{cid: 1, clbl: 'Rush Shipping', pid:5, plbl: 'FedEx'},
{cid: 2, clbl: 'Standard Shipping', pid:5, plbl: 'FedEx'},
{cid: 3, clbl: 'First Class', pid:8, plbl: 'USPS'},
{cid: 4, clbl: 'Std', pid:9, plbl: 'DHL'},
{cid: 5, clbl: 'Canada Post', pid:1, plbl: 'Canada Post'},
];
I would like my output to be something like this:
[ { pid: 5,
plbl: 'FedEx',
methods: [
{
cid: 1,
clbl: 'Rush Shipping',
},
{
cid: 2,
clbl: 'Standard Shipping',
},
},
{ pid: 8,
plbl: 'USPS',
methods: [
{
cid: 3,
clbl: 'First Class',
},
},
{ pid: 9,
plbl: 'DHL',
methods: [
{
cid: 4,
clbl: 'Std',
},
},
{ pid: 1,
plbl: 'Canada Post',
methods: [
{
cid: 5,
clbl: 'Canada Post',
},
},
]
I threw together some code that works, but I imagine there has be be a more optimized way to do this and thought I would put it to the SO community.
Here's my solution:
var roots = [];
var all = {};
data.forEach(function(item) {
all[item.pid] = item;
})
Object.keys(all).forEach(function(pid) {
var items = data.filter(x => x.pid == pid);
var addItem = {};
items.forEach(function(item, j) {
if (j === 0){
addItem = {pid:item.pid, label:item.plbl, methods:[]};
}
addItem.methods.push({cid: item.cid, label: item.clbl});
});
roots.push(addItem);
})
console.log(roots);