The Wayback Machine - https://web.archive.org/web/20240927010612/https://www.geeksforgeeks.org/how-to-create-an-array-of-objects-from-multiple-arrays-in-javascript/
Open In App

How to create an array of objects from multiple arrays in JavaScript ?

Last Updated : 30 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Creating an array of objects from multiple arrays in JavaScript involves combining corresponding elements from each array into single objects. This approach allows you to efficiently organize related data from separate arrays into a structured format, making it easier to manipulate and access the combined information.

Below are the approaches used to create an array of objects from multiple arrays in JavaScript:

Using a Loop

This approach uses a for loop to iterate through the keys and values arrays, creating an object for each pair and pushing it into an array. The resulting array contains objects with keys from the keys array and corresponding values from the values array.

Example: This example uses a Loop

JavaScript
function createArrayOfObjectsUsingLoop(keys, values) {
    let arrayOfObjects = [];

    for (let i = 0; i < Math.min(keys.length, values.length); i++) {
        let obj = {};
        obj[keys[i]] = values[i];
        arrayOfObjects.push(obj);
    }

    return arrayOfObjects;
}

// Example usage:
let keysArray = ['name', 'age', 'city'];
let valuesArray = ['John', 25, 'New York'];
let resultUsingLoop = createArrayOfObjectsUsingLoop(keysArray, valuesArray);
console.log(resultUsingLoop);

Output
[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]

Using map Function

The map function is employed to create an array of objects. For each element in the keys array, an object is created with a key-value pair, where the key is from the keys array, and the value is from the corresponding position in the values array.

Example: This example uses map Function

JavaScript
function createArrayOfObjectsUsingMap(keys, values) {
    return keys.map(function (key, index) {
        let obj = {};
        obj[key] = values[index];
        return obj;
    });
}

// Example usage:
let keysArrayMap = ['name', 'age', 'city'];
let valuesArrayMap = ['John', 25, 'New York'];
let resultUsingMap = createArrayOfObjectsUsingMap(keysArrayMap, valuesArrayMap);
console.log(resultUsingMap);

Output
[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]

Using reduce Function

In this approach, the reduce function is used to accumulate objects into an array. For each element in the keys array, an object is created with a key-value pair, and it is pushed into the accumulator array.

Example: This example uses reduce Function

JavaScript
function createArrayOfObjectsUsingReduce(keys, values) {
    return keys.reduce(function (acc, key, index) {
        let obj = {};
        obj[key] = values[index];
        acc.push(obj);
        return acc;
    }, []);
}

// Example usage:
let keysArrayReduce = ['name', 'age', 'city'];
let valuesArrayReduce = ['John', 25, 'New York'];
let resultUsingReduce = createArrayOfObjectsUsingReduce(keysArrayReduce, valuesArrayReduce);
console.log(resultUsingReduce);

Output
[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]

Using Object.fromEntries() method along with the map function

This method utilizes Object.fromEntries() along with the map function to create an array of objects. It first zips the keys and values arrays into an array of key-value pairs and then uses Object.fromEntries() to convert each pair into an object.

Example: This example uses Object.fromEntries()

JavaScript
function createArrayOfObjectsUsingFromEntries(keys, values) {
    // Ensure both arrays have the same length
    const minLength = Math.min(keys.length, values.length);


    const keyValuePairs = keys.slice(0, minLength).map((key, index) => [key, values[index]]);

    
    const arrayOfObjects = keyValuePairs.map(pair => Object.fromEntries([pair]));

    return arrayOfObjects;
}

// Example usage:
let keysArrayFromEntries = ['name', 'age', 'city'];
let valuesArrayFromEntries = ['John', 25, 'New York'];
let resultUsingFromEntries = 
    createArrayOfObjectsUsingFromEntries(keysArrayFromEntries, valuesArrayFromEntries);
console.log(resultUsingFromEntries);

Output
[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]

Using Array.forEach()

To create an array of objects from multiple arrays in JavaScript using Array.forEach(), iterate over the keys array. For each key, push an object into the result array with the corresponding value from the values array.

Example: In this example we creates an array of objects by pairing elements from two arrays (keys and values). It iterates over keys, using each key to create an object with its corresponding value from values.

JavaScript
const keys = ['name', 'age', 'gender'];
const values = ['Alice', 30, 'female'];

const arrayOfObjects = [];
keys.forEach((key, index) => {
  arrayOfObjects.push({ [key]: values[index] });
});

console.log(arrayOfObjects); 

Output
[ { name: 'Alice' }, { age: 30 }, { gender: 'female' } ]

Using a Custom Zip Function and map

In this method, we’ll first create a custom zip function that combines two arrays into an array of pairs. Then, we’ll use map to convert these pairs into objects.

Custom Zip Function

The custom zip function combines two arrays into an array of arrays where each inner array contains corresponding elements from the input arrays.

Implementation

  1. Define the zip Function: This function pairs elements from two arrays into sub-arrays.
  2. Transform Pairs into Objects: Use map to create an object for each pair.

Example:

JavaScript
function zip(array1, array2) {
    const length = Math.min(array1.length, array2.length);
    const zipped = [];
    for (let i = 0; i < length; i++) {
        zipped.push([array1[i], array2[i]]);
    }
    return zipped;
}
function createArrayOfObjects(keys, values) {
    const pairs = zip(keys, values);
    return pairs.map(([key, value]) => ({ [key]: value }));
}
const keysArray = ['name', 'age', 'city'];
const valuesArray = ['John', 25, 'New York'];
const result = createArrayOfObjects(keysArray, valuesArray);

console.log(result);

Output
[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]



Similar Reads

How to create an array with multiple objects having multiple nested key-value pairs in JavaScript ?
In this article, we will learn to create an array with multiple objects having key-value pairs, we will use nesting which means defining another array in a pre-defined array with key-value pairs. Suppose we have several arrays of objects means containing various key-value pairs where keys are uniquely identified now we have to add these arrays to a
3 min read
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
5 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
7 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing Set for Efficient FilteringUsi
3 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
8 min read
How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
7 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to updating an array of objects with another array of objects in the Lodash library: Table of Content Using lodash _.merge() function Using lodash _.mergeWith()
4 min read
How to group objects in an array based on a common property into an array of arrays in JavaScript ?
In this article, we will try to understand how we may easily group objects in an array based on a common property into an array of arrays in JavaScript with the help of an example itself. Grouping objects in an array based on a common property into an array of arrays in JavaScript. Organize data by shared property for efficient data manipulation. S
6 min read
JavaScript Program to Create an Array of Unique Values From Multiple Arrays Using Set Object
We have given multiple arrays consisting of numerical values, and our task is to create an output array that consists of unique values from the multiple input arrays. We will use the Set object in JavaScript language. Example: Input: inputarray1: [1,2,3,4,5] inputarray2: [4,5,6,7,8] Output: outputArray: [1,2,3,4,5,6,7,8]Table of Content Using Set a
5 min read
Extract unique objects by attribute from array of objects
Given an array of objects and the task is to return the unique object by the attribute. Examples: Input: [ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 } ]Output:[ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 } ]Approach: Let's assume that name is an attribute that di
4 min read
Get list of Duplicate Objects in an Array of Objects
Finding duplicates in an array of objects is a common task in JavaScript, especially when dealing with data manipulation and validation. This will guide you through the process of identifying duplicate objects in an array using various techniques. Understanding the ProblemLet's assume we have an array of objects where each object has a set of key-v
4 min read
How to Convert Object Containing Objects into Array of Objects using Lodash?
Lodash is a JavaScript utility library that provides predefined functions to make code more readable and cleaner. These functions are optimized for performance, often being faster than native JavaScript methods for complex operations.We will learn how to convert an object containing objects into an array of objects using Lodash. There are two appro
4 min read
How to find property values from an array containing multiple objects in JavaScript ?
To find property values from an array containing multiple objects in JavaScript, we have multiple approaches. In this article, we will learn how to find property values from an array containing multiple objects in JavaScript. Several methods can be used to find property values from an array containing multiple objects. Table of Content Using for-lo
4 min read
How to Filter an Array of Objects Based on Multiple Properties in JavaScript ?
Filtering an array of objects based on multiple properties is a common task in JavaScript. It allows us to selectively extract items from an array that satisfy specific conditions. We will explore different approaches to achieve this task. These are the following approaches: Table of Content Using the filter() MethodUsing a for LoopUsing Array.from
6 min read
How to create an array of partial objects from another array in JavaScript ?
Creating an array of partial objects from another array is a useful technique in JavaScript, especially for data transformation and manipulation. This guide covers various methods to efficiently create these arrays, enhancing your ability to work with complex data structures. Importance of Creating Partial Objects:Creating partial objects is crucia
6 min read
How to Convert an Array of Objects into an Array of Arrays ?
An Array of objects is an array that contains multiple objects as its elements which can be converted into an array of arrays i.e. an array that contains multiple arrays as its elements. There are several methods listed below to achieve this task. Table of Content Using Object.keys() and Object.values() methodsUsing Javascript map() methodUsing Jav
3 min read
What is the difference between Host objects and Native objects ?
In this article, we will learn about what are Host objects and Native objects, and their differences. JavaScript objects are broadly classified into 2 categories - native javascript objects and host javascript objects. Native objects: Native javascript objects are standard javascript objects which are provided by javascript itself. They are also kn
2 min read
How to Create Nested Arrays from a Nest of Arrays in JavaScript ?
Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional structures. Such nested arrays can represent various dat
3 min read
How to Merge two Different Arrays of Objects with Unique Values in JavaScript?
Merging two arrays of objects with unique values is a common task in JavaScript. This operation involves combining the elements of two arrays while ensuring that each resulting object has a unique identifier. We will explore various approaches to merging two arrays of objects with unique values. These are the following approaches: Table of Content
5 min read
How to Remove Null Objects from Nested Arrays in JavaScript ?
Javascript arrays are a very flexible container that can hold both elements or values. Nevertheless, with nested arrays, it is crucial for data management and cleaning. Replacing null objects is a frequent demand. Below are the methods to remove null objects from nested arrays in JavaScript: Table of Content Using Filter() MethodUsing Set MethodUsi
9 min read
How to compare Arrays of Objects in JavaScript?
In JavaScript, comparing arrays of objects can be more complex than comparing primitive data types. We will discuss different ways to compare arrays of objects effectively, with detailed code examples and explanations. Syntax: Before going to detail the comparison techniques, let's first understand how to declare an array of objects in JavaScript:
5 min read
How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object. Below approaches can be used to accomplish this taskTable of Content Using Object.keys() and re
3 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How to pass multiple JSON Objects as data using jQuery's $.ajax() ?
The purpose of this article is to pass multiple JSON objects as data using the jQuery $ajax() method in an HTML document. Approach: Create a button in an HTML document to send JSON objects to a PHP server. In the JavaScript file, add a click event listener to the button. On clicking of the button, a request is made to PHP file using jQuery $ajax()
3 min read
How to merge multiple inline style objects ?
In this article, we will learn about the Multiple inline styles. Multiple inline styles can be merged in two ways both ways are described below: Table of Content Using Spread operator:Using Object.assign(): Method 1: Using Spread Operator:The ... operator is called a spread operator. The spread operator in this case concatenates both the objects in
2 min read
Difference between Array and Array of Objects in JavaScript
ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored in an array. Example: In thi
3 min read
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to convert an array of objects to a map in JavaScript:
2 min read
Replace multiple strings with multiple other strings in JavaScript
In this article, we are given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using JavaScript. Below are a few methods to understand: Table of Content Using JavaScript replace() method Using the JavaScript str.replaceAll() methodUsing Array.reduce() method:
2 min read
How to Create Dynamic Values and Objects in JavaScript?
In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array, Dynamic values and objects in JavaScript allow changing, accessing, or creating values and object properties at runtime for flexibility and adaptability. Below are the approaches to create d
3 min read
How to find Objects that Contain the same Elements from Arrays in Another Object ?
To find objects containing identical elements as specified arrays within another object, iterate through the objects. Identify those whose elements match the provided arrays. This involves comparing the presence of identical elements, ensuring all elements from the arrays exist within the target objects. There are various methods to achieve this wh
3 min read