Reputation: 571
I need to normalize the api response data with deeply nested structure. I am using this https://github.com/paularmstrong/normalizr to normalize my data.
I have a input data as
const data = [{
id: 'component1,
name: 'component one,
properties:[{
name: 'text',
color: 'red'
}]
},
{
id: 'component2,
name: 'component two',
properties:[{
name: 'text',
color: 'yellow'
},{
name: 'button',
color: 'blue'
}]
}]
Expected output after normalization
{
entities: {
component1: {
id: 'component1,
name: 'component one,
properties: {
entities: {
text: {
name: 'text',
color: 'red'
}
},
results: ['text']
}
},
component2: {
id: 'component2,
name: 'component two,
properties: {
entities: {
text: {
name: 'text',
color: 'yellow'
},
button: {
name: 'button',
color: 'blue'
}
},
results: ['text', 'button']
}
}
},
results: ['component1', 'component2']
}
Any help please
Upvotes: 0
Views: 819
Reputation: 2293
This is my approach, iterate all data using forEach()
in order to rearrange it in the format you want:
const data = [{id: 'component1',name: 'component one',properties:[{name: 'text',color: 'red'}]},{id: 'component2',name: 'component two',properties:[{name: 'text',color: 'yellow'},{name: 'button',color: 'blue'}]}];
let result = {entities: {}, result: []};
data.forEach(c => {
result.result.push(c.id);
result.entities[c.id] = {
id: c.id,
name: c.name,
properties: {
entities: Object.fromEntries(c.properties.map(p => [p.name, p])),
results: c.properties.map(p => p.name)
}
};
});
console.log(result);
Upvotes: 1