I want to create an array of objects, and the first elements from the each data object to be a separate object, the second element from the each data object to be another separate object and so on...
let array = [{
data: {
center1: "1",
storage1: "1",
system1: "1",
}
},
{
data: {
center2: "2",
storage2: "2",
system2: "2",
}
}
]
Expected result:
[
{ center1: "1", center2: "2"},
{ storage1: "1", storage2: "2"},
{ system1: "1", system2: "2"}
]
And this is what I tried do to but is not working really well:)
const rows = [];
array.forEach((item, index) => {
for (let key in item.data) {
rows.push({index : key + ': ' + item.data[key]});
}
});
The output is this:
[
{index : 'center1: 1'},
{index : 'storage1: 1'},
{index : 'system1: 1'},
{index : 'center2: 2'},
{index : 'storage2: 2'},
{index : 'system2: 2'}
]
Thank you for your help!
This'll be incredibly brittle, because key ordering is irrelevant to how JS objects work, and the assumption that "the first key in each object is the same kind of key" is really only that: an assumption. So, the first thing to fix would be to make all those objects use the same keys, not uniques, thus making "key ordering" irrelevant.
However, if that's not an option (and it almost certain is, but if it's not) then Object.entries will turn any object into a key/value array, which you can then use to restructure this data:
let array = [{
data: {
center1: "1",
storage1: "1",
system1: "1",
}
},
{
data: {
center2: "2",
storage2: "2",
system2: "2",
}
}
]
const restructured = array.reduce((result, e) => {
Object.entries(e.data).forEach(([key, val], pos) => {
if (!result[pos]) result[pos] = {};
result[pos][key] = val;
});
return result;
}, []);
console.log(restructured);
let array = [{
data: {
center1: "1",
storage1: "1",
system1: "1",
}
},
{
data: {
center2: "2",
storage2: "2",
system2: "2",
}
}
]
const rows = [];
array.forEach(item => {
Object.keys(item.data).forEach( (dt, i) => {
if ( ! rows[i] ) {
rows.push({});
}
rows[i][dt] = item.data[dt];
});
});
console.log(rows)
You can try something like this, which may probably optimized (of course it will work only if all objects strictly have the same structure) :
const array = [
{
data: {
center1 : "1",
storage1: "1",
system1 : "1",
}
},
{
data: {
center2 : "2",
storage2: "2",
system2 : "2",
}
}
];
const finalArray = [];
for (let i = 0; i < Object.keys(array[0].data).length; i++) {
finalArray.push({});
array.forEach(arrayItem => {
finalArray[i][Object.keys(arrayItem.data)[i]] = Object.values(arrayItem.data)[i]
});
}
console.log(finalArray)