How to convert an object type to two dimensional array in lodash?

55 Views Asked by At

I need to convert an object type to an array of different objects in order to display several tables in my angular project.

Below is my object:

let myObject = {
  internalValue:{city:"Paris", country:"France", pinCode:12345}, 
  originalValue:{city:"Nantes", country:"France", pinCode:34567}, 
  score:{city:10, country:100, pinCode:45}
};

Expected Array

[
  [
    {detail:"Paris", label:"internalValue"},
    {detail:"Nantes", label:"originalValue"},
    {detail:10, label:"score"}
  ],
  [
    {detail:"France", label:"internalValue"},
    {detail:"France", label:"originalValue"},
    {detail:100, label:"score"}
  ],
  [
    {detail:12345, label:"internalValue"},
    {detail:34567, label:"originalValue"},
    {detail:45, label:"score"}
  ]
]

My code

let tableData:any;
tableData = _.transform(myObject, result, value, key)=>{
  let retValue:any;
  _.forIn(value, (v,k)=> {
    let tempArr:Array<any>;
    let tempObj:any = {};
    tempObj.detail= v;
    tempObj.label=key;
    tempArr.push(tempObj);
    retValue.push(tempArr);
  })
  result = [...retValue];
  return result;
},[]);

Stuck here for the next set of loops.

3

There are 3 best solutions below

0
Joshua Varghese On

Lodash isn't really required here. You could do this by using the Object.keys and Object.values to iterate over the properties of the objects.

Here you initially get the required keys (city, country, pinCode) from 1st value in the object and iterate over. Below is an example:

let myObject = {
  internalValue:{city:"Paris", country:"France", pinCode:12345}, 
  originalValue:{city:"Nantes", country:"France", pinCode:34567}, 
  score:{city:10, country:100, pinCode:45}
};

let keys = Object.keys(myObject);
let values = Object.values(myObject);

let result = Object.keys(values[0]).map((_, i) => {
  return keys.map(key => {
    return {detail: myObject[key][Object.keys(values[0])[i]], label: key};
  });
});

console.log(result);
1
Ori Drori On

Create an array of keys you wish to extract (fields in the example). Use Object.entries() on the original object to get an array of [key, value] pairs (entries in the example). Now map the fields, and map the entries to create an array for each field:

const fields = ['city', 'country', 'pinCode'];

const fn = obj => {
  const entries = Object.entries(obj);

  return fields.map(field => 
    entries.map(([label, val]) => ({
      detail: val[field],
      label
    }))
  );
};

const myObject = {
  internalValue:{city:"Paris", country:"France", pinCode:12345}, 
  originalValue:{city:"Nantes", country:"France", pinCode:34567}, 
  score:{city:10, country:100, pinCode:45}
};

const result = fn(myObject);

console.log(result);

0
Vivick On

Here's how you can achieve this using lodash:

let myObject = {
  internalValue:{city:"Paris", country:"France", pinCode:12345}, 
  originalValue:{city:"Nantes", country:"France", pinCode:34567}, 
  score:{city:10, country:100, pinCode:45}
};

const toDetails = (obj, keys = _.chain(obj).values().map(_.keys).first().value()) => {
   // OR keys = Object.keys(Object.values(obj)[0])

    return keys.map(key => {
        return _.chain(obj)
        .mapValues(key)
        .map((detail, label) => ({ detail, label }))
        .value();
    });
};

const explicit = toDetails(myObject, ["city", "country", "pinCode"]);
console.log("explicit", explicit);

const implicit = toDetails(myObject);
console.log("implicit", implicit);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>