ThexBasic - 13 days ago 4

Javascript Question

so I'm having this weird problem that one of my node js library's 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)

I'm pretty sure this is a repost question, but couldn't find anything under my search terms. So please forgive me, I'm a bit desperate about this one.

Thanks in advance.

Answer

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;
}, []);
}
```