0

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?

asked Jul 10, 2020 at 9:13

2 Answers 2

1

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);

answered Jul 10, 2020 at 10:34
Sign up to request clarification or add additional context in comments.

Comments

0

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]
 })
}
answered Jul 10, 2020 at 9:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.