skip to Main Content

How to convert object of arrays collections into array of object

From

const obj = {
  name: ['Sam', 'John', 'Paul'],
  age: [25, 35, 22],
  profession: ['Developer', 'Tester', 'Manager']
}

To

const collections = [
  {name: 'Sam', age: 25, profession: 'Developer'},
  {name: 'John', age: 35, profession: 'Tester'},
  {name: 'Paul', age: 22, profession: 'Manager'}
]

2

Answers


  1. Here are two ways to convert an object of arrays into an array of objects in JavaScript:

    Method 1: Using map and Object.values:

    JavaScript

    const obj = {
      name: ['Sam', 'John', 'Paul'],
      age: [25, 35, 22],
      profession: ['Developer', 'Tester', 'Manager']
    };
    
    const collections = Object.values(obj[0]).map((value, index) => ({
      name: obj.name[index],
      age: obj.age[index],
      profession: obj.profession[index]
    }));
    
    console.log(collections);
    // Output:
    // [
    //   { name: 'Sam', age: 25, profession: 'Developer' },
    //   { name: 'John', age: 35, profession: 'Tester' },
    //   { name: 'Paul', age: 22, profession: 'Manager' }
    // ]
    

    Use code with caution. Learn more
    Explanation:

    Object.values(obj[0]) extracts the values of the first array in the object (the names).
    The map method iterates over these values and creates a new object for each one, using the corresponding values from the other arrays.
    Method 2: Using nested forEach loops:

    JavaScript

    const collections = [];
    
    Object.keys(obj).forEach((key) => {
      obj[key].forEach((value, index) => {
        if (!collections[index]) {
          collections[index] = {};
        }
        collections[index][key] = value;
      });
    });
    
    console.log(collections);
    

    Use code with caution. Learn more
    Explanation:

    The outer forEach loop iterates over the keys of the object.
    The inner forEach loop iterates over the values of each array.
    It creates a new object in the collections array if it doesn’t exist yet, and assigns the value to the corresponding key.
    Key points:

    Assumed Array Length: Both methods assume that all arrays within the object have the same length.
    Conciseness: The first method using map and Object.values is generally more concise and readable.
    Readability: The second method using nested forEach loops might be more intuitive for those less familiar with map.
    Choose the method that you find more comfortable and understandable!

    Login or Signup to reply.
  2. Here is an example of a simple way to get an array of objects from object of arrays as above by using reduce:

    const obj = {
        name: ['Sam', 'John', 'Paul'],
        age: [25, 35, 22],
        profession: ['Developer', 'Tester', 'Manager'],
      };
    
    const collection = Object.entries(obj).reduce((collectionArray, [key, arrayValues]) => {
        arrayValues.forEach((value, index) =>
          index < collectionArray.length
            ? (collectionArray[index][key] = value)
            : collectionArray.push({ [key]: value })
        );
        return collectionArray;
      }, []);
    
    console.log(collection)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search