I would like to transform an object to an array format. The input object is
{
"index": {
"0": 40,
"1": 242
},
"TID": {
"0": "11",
"1": "22"
},
"DepartureCity": {
"0": "MCI",
"1": "CVG"
},
"ArrivalCity": {
"0": "SFB",
"1": "LAS"
},
"Price": {
"0": 90,
"1": 98
}
}
And the expected output is
[
{
"index": 40,
"TID": "11",
"DepartureCity": "MCI",
"ArrivalCity": "SFB",
"Price": 90
},
{
"index": 242,
"TID": "22",
"DepartureCity": "CVG",
"ArrivalCity": "LAS",
"Price": 98
}
]
I tried using for loops, but it is getting more complicated. If any one can help me, it would be really thankful.
Here is a lodash
approach
_.merge([], ..._.map(obj, (v, k) => _.mapValues(v, ev=> ({[k]:ev}))))
let inputObj = {
"index": {
"0": 40,
"1": 242
},
"TID": {
"0": "11",
"1": "22"
},
"DepartureCity": {
"0": "MCI",
"1": "CVG"
},
"ArrivalCity": {
"0": "SFB",
"1": "LAS"
},
"Price": {
"0": 90,
"1": 98
}
};
let res = _.merge([], ..._.map(inputObj, (v, k) => _.mapValues(v, ev=> ({[k] :ev}))));
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Try reduce
-ing the entries
into an array of objects, iterating over each value of the inner objects:
const input={"index":{"0":40,"1":242},"TID":{"0":"11","1":"22"},"DepartureCity":{"0":"MCI","1":"CVG"},"ArrivalCity":{"0":"SFB","1":"LAS"},"Price":{"0":90,"1":98}}
const output = Object.entries(input).reduce((a, [key, obj]) => {
Object.values(obj).forEach((val, i) => {
if (!a[i]) a[i] = {};
a[i][key] = val;
});
return a;
}, []);
console.log(output);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With