I have a dataset as below,
// e.g.
[{
id: 'M1',
description: 'Lorem description',
fields: [{
name: 'field_1',
value: 'Lorem value 1'
}]
}]
which I need to transform into,
[
{
id: 'M1',
description: 'Lorem description',
field_1: 'Lorem value 1'
}
]
I wrote the code below to accomplish this. And it works well, but I don't think this is the best way to do it. How can I make my solution better performing? Because this is slower when the dataset gets larger.
const _sampleData = [{
id: 'M1',
description: 'Lorem description',
fields: [{
name: 'field_1',
value: 'Lorem value 1'
}]
},
{
id: 'M2',
description: 'Lorem description',
fields: [{
name: 'field_1',
value: 'Lorem value 1'
},
{
name: 'field_2',
value: 'Lorem value 2'
}
]
}
];
function toObject(fields) {
const out = {};
for (const field of fields) {
out[field.name] = field.value;
}
return out;
}
function getFlatSampleData() {
const data = [];
for (const item of _sampleData) {
let out = {};
for (const key in item) {
if (Array.isArray(item[key])) {
out = {
...out,
...toObject(item[key])
};
} else {
out[key] = item[key];
}
}
data.push(out);
}
return data;
}
console.log(getFlatSampleData());