How can we make an Array of Objects from n properties of n arrays in JavaScript?

When working with multiple arrays in JavaScript, you often need to combine them into an array of objects. This is useful for creating structured data from separate arrays of related information.

Suppose we have two arrays of literals like these:

const options = ['A', 'B', 'C', 'D'];
const values = [true, false, false, false];

We need to create a JavaScript function that combines these arrays into a new array of objects like this:

[
  {opt: 'A', val: true},
  {opt: 'B', val: false},
  {opt: 'C', val: false},
  {opt: 'D', val: false}
]

Method 1: Using a For Loop

The traditional approach uses a for loop to iterate through the arrays and create objects:

const options = ['A', 'B', 'C', 'D'];
const values = [true, false, false, false];

const mapArrays = (options, values) => {
    const res = [];
    for(let i = 0; i < options.length; i++){
        res.push({
            opt: options[i],
            val: values[i]
        });
    }
    return res;
};

console.log(mapArrays(options, values));
[
  { opt: 'A', val: true },
  { opt: 'B', val: false },
  { opt: 'C', val: false },
  { opt: 'D', val: false }
]

Method 2: Using Array.map()

A more functional approach uses the map() method for cleaner, more concise code:

const options = ['A', 'B', 'C', 'D'];
const values = [true, false, false, false];

const mapArraysWithMap = (options, values) => {
    return options.map((opt, index) => ({
        opt: opt,
        val: values[index]
    }));
};

console.log(mapArraysWithMap(options, values));
[
  { opt: 'A', val: true },
  { opt: 'B', val: false },
  { opt: 'C', val: false },
  { opt: 'D', val: false }
]

Method 3: Handling Multiple Arrays

For more than two arrays, you can extend the approach:

const options = ['A', 'B', 'C'];
const values = [true, false, true];
const colors = ['red', 'blue', 'green'];

const mapMultipleArrays = (options, values, colors) => {
    return options.map((opt, index) => ({
        opt: opt,
        val: values[index],
        color: colors[index]
    }));
};

console.log(mapMultipleArrays(options, values, colors));
[
  { opt: 'A', val: true, color: 'red' },
  { opt: 'B', val: false, color: 'blue' },
  { opt: 'C', val: true, color: 'green' }
]

Comparison

Method Readability Performance Best For
For Loop Good Fast Large datasets
Array.map() Excellent Good Functional programming style

Conclusion

Use Array.map() for cleaner, more readable code when combining arrays into objects. The for loop approach works well for performance-critical applications with large datasets.

Updated on: 2026-03-15T23:18:59+05:30

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements