Reputation: 714
One of my node js libraries is returning some data I need in the wrong format like this:
{"a":["1","2"],"b":["3","4"],"c":["5","6"]}
(note that the values don't matter) but I need to loop this array in a way, that I find my B for my A that has a certain value (in this case e.g. '2', I would need '4') and all other parts of my program are so far using arrays like this:
[{"a":"1", "b":"3", "c":"5"}, {"a":"2", "b":"4", "c":"6"}]
and it would be my preferred approach.
Also note that the amount of data in a is always the same as b and c, but itself is variable.
So what would be the "best" way to accomplish this in ES6/JS (before I start messing with for-loops)?
Upvotes: 2
Views: 137
Reputation: 81
If you are looking to transform an object like
{"a":["1","2"],"b":["3","4"],"c":["5","6"]}
Into a array like
[{"a":"1","b":"3","c":"5"},{"a":"2","b":"4","c":"6"}]
Something like this is the simplest way I can think of
function formatData (data) {
return Object.keys(data).reduce((arr, key) => {
data[key].forEach((value, i) => {
const iObj = arr[i] || (arr[i] = {});
iObj[key] = value;
});
return arr;
}, []);
}
Upvotes: 2