The code below reduces an array into "named" objects (not sure if that's the correct terminology!)
It works, but I'm sure the code could be improved. There is some repetition going on in the reduce.
It checks if a key exists (if (accumulator[name])
). If not then initialize the results
array, if it does then push onto the results
array.
let response = {
columns: [
'n'
],
data: [
{
graph: {
nodes: [
{
id: '169',
labels: [
'Container'
],
properties: {
reference: 'REF002',
name: 'Cupboard',
id: '003'
}
}
],
relationships: []
}
},
{
graph: {
nodes: [
{
id: '170',
labels: [
'Container'
],
properties: {
reference: 'REF003',
name: 'Cupboard A',
id: '03a'
}
}
],
relationships: []
}
},
{
graph: {
nodes: [
{
id: '964',
labels: [
'Equipment'
],
properties: {
reference: 'REF004',
name: 'Cupboard B',
id: '03b'
}
}
],
relationships: []
}
}
]
}
const result = response.data.reduce(
(accumulator, currentValue, currentIndex, array) => {
const name = currentValue.graph.nodes[0].labels[0];
if (accumulator[name]) {
accumulator[name].results.push({
title: currentValue.graph.nodes[0].properties.name,
description: currentValue.graph.nodes[0].properties.reference
});
} else {
accumulator[name] = {
name,
results: [
{
title: currentValue.graph.nodes[0].properties.name,
description: currentValue.graph.nodes[0].properties.reference
}
]
};
}
return accumulator;
},
{}
);
console.clear();
console.log(result);
Output Required
{
Container: {
name: 'Container',
results: [
{
title: 'Cupboard',
description: 'REF002'
},
{
title: 'Cupboard A',
description: 'REF003'
}
]
},
Foo: {
name: 'Foo',
results: [
{
title: 'Cupboard B',
description: 'REF004'
}
]
}
}