I've a druid cluster that I'm querying with the plywood library.
Data are retrieved as arrays of objects. Everything is fine, but now I've now to reshape those data to have a better visualization in my table.
This is my array:
var x_start = [
{ split: 'no', c1: 345, c2: 763, c3: 12 },
{ split: 'yes', c1: 293, c2: 1283, c3: 46 },
];
x_start will always have 2 object with the same keys.
And this is what i want to accomplish:
var x_target = [
{ cluster: 'c1', no: 345, yes: 293 },
{ cluster: 'c2', no: 763, yes: 1283 },
{ cluster: 'c3', no: 12, yes: 46 },
];
I made some researches and I understand that the best solution is probably to use a combination of map for accessing the objects and then reshaping them, but I'm in trouble to find the correct way to do that.
Any suggestion?
2 Answers 2
You can try with Array.prototype.reduce() and Array.prototype.find() to solve your problem. You can checkout the following solution.
var x_start = [{
split: 'no',
c1: 345,
c2: 763,
c3: 12
},
{
split: 'yes',
c1: 293,
c2: 1283,
c3: 46
},
];
const reducer = (acc, x) => {
const findOrAdd = key => {
let item = acc.find(v => v.cluster === key);
if (item) return item;
item = {
cluster: key
};
acc.push(item);
return item;
}
Object.keys(x).filter(key => key !== 'split')
.forEach(key => {
const item = findOrAdd(key);
item[x.split] = x[key];
});
return acc;
}
var x_target = x_start.reduce(reducer, []);
console.log(x_target);
Comments
This will work if x_start only has 2 objects and the number of c1, c2..cn in no is equal to c1, c2..cn in yes
const no_arr = Object.entries(x_start[0]);
const yes_arr = Object.entries(x_start[1]);
const x_target = [];
for (let i = 1; i < no_arr.length; i++) {
x_target.push({
'cluster': no_arr[i][0],
'no': no_arr[i][1],
'yes': yes_arr[i][1]
})
}