skip to Main Content

I am having an object in the below format where name, age and gender are the column names and the object assigned to them are values of that column.

{
  'name': {
    0: 'Alpha',
    1: 'Beta',
    2: 'Gamma'
  },
  'age': {
    0: 21,
    1: 25,
    2: 30
  },
  'gender': {
    0: 'Male',
    1: 'Female',
    2: 'Male'
  }
}

I want to convert above object into an array of objects.

Expected output :

[{
    name: 'Alpha',
    age: 21,
    gender: 'Male'
}, {
    name: 'Beta',
    age: 25,
    gender: 'Female'
}, {
    name: 'Gamma',
    age: 30,
    gender: 'Male'
}]

What I tried so far ?

I tried with Object.keys() to create the initial object with the keys first {name: '', age: '', gender: ''} and then tried to iterate over the values of each key with the help of Object.values() method to bind the each index values dynamically against each key of the object but not able to achieve.

const obj = {
  'name': {
    0: 'Alpha',
    1: 'Beta',
    2: 'Gamma'
  },
  'age': {
    0: 21,
    1: 25,
    2: 30
  },
  'gender': {
    0: 'Male',
    1: 'Female',
    2: 'Male'
  }
};

const columnNameObj = {}
const arr = []
Object.keys(obj).forEach(column => {
  Object.values(obj[column]).forEach((item, index) => {
    columnNameObj[column] = obj[column][index] // <-- Here I am doing a mistake as it iterates the whole loop and the last value get assigned to the object property. Object should be pushed on each iteration instead of ending the inner loop but somehow I am stuck here.
  })
  arr.push(columnNameObj);
})

console.log(arr);

2

Answers


  1. Since your nested values are indexed with sequential integers, you can use these keys to access the relevant index in the result array within a nested loop.
    Here using nullish coallescing assignment (??=) to initialize each result object if it doesn’t already exist.

    const input = { name: { 0: 'Alpha', 1: 'Beta', 2: 'Gamma', }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: 'Male', 1: 'Female', 2: 'Male', }, };
    
    const result = [];
    
    for (const [key, values] of Object.entries(input)) {
      for (const [index, value] of Object.entries(values)) {
        (result[index] ??= {})[key] = value;
      }
    }
    
    console.log(result);

    Or using the same logic in a reduce() call with a nested forEach() if you prefer.

    const input = { name: { 0: 'Alpha', 1: 'Beta', 2: 'Gamma', }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: 'Male', 1: 'Female', 2: 'Male', }, };
    
    const result = Object.entries(input).reduce((a, [key, values]) => {
      Object.entries(values).forEach(([index, value]) => {
        (a[index] ??= {})[key] = value;
      });
      return a;
    }, []);
    
    console.log(result);
    Login or Signup to reply.
  2. You can try array reduce

    const data = {
      'name': {
        0: 'Alpha',
        1: 'Beta',
        2: 'Gamma'
      },
      'age': {
        0: 21,
        1: 25,
        2: 30
      },
      'gender': {
        0: 'Male',
        1: 'Female',
        2: 'Male'
      }
    }
    const dataKeys = Object.keys(data);
    const vals = Object.values(data).reduce((acc, curr) => {
      let obj = {};
      // key will be 0,1,2, this is used to get the value from the index
      for (let key in curr) {
        obj[dataKeys[key]] = curr[key]
      }
      acc.push(obj)
    
      return acc;
    
    
    }, []);
    console.log(vals)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search