Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform objects to array using lodash

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.

like image 836
Rajeshwar Avatar asked Mar 06 '23 14:03

Rajeshwar


2 Answers

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>
like image 62
Koushik Chatterjee Avatar answered Mar 16 '23 02:03

Koushik Chatterjee


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);
like image 25
CertainPerformance Avatar answered Mar 16 '23 00:03

CertainPerformance