How to Push Key-Value Pair Into an Array Using JavaScript

Mehvish Ashiq Feb 02, 2024
  1. Push Key-Value Pair Into an Array Using JavaScript
  2. Use map() to Push Key-Value Pair Into an Array in JavaScript
  3. Use reduce() to Push Key-Value Pair Into an Array in JavaScript
  4. Use jQuery to Push Key-Value Pair Into an Array in JavaScript
  5. Conclusion
How to Push Key-Value Pair Into an Array Using JavaScript

This article delves into various methods to push key-value pairs into an array using JavaScript, focusing on different approaches, from manual object creation to leveraging built-in functions.

Demonstrating code snippets and their respective outputs, we’ll explore techniques like for loops, map(), reduce(), and even the use of jQuery’s $.each() function.

By understanding these techniques, you’ll have a comprehensive toolkit to efficiently organize and manipulate data within arrays.

Push Key-Value Pair Into an Array Using JavaScript

Let’s begin by exploring a method to achieve this without using built-in functions and methods in JavaScript.

JavaScript Code:

var arr1 = ['left', 'top'], arr2 = [];
var obj = {};

for (i = 0; i < arr1.length; i++) {
  obj[arr1[i]] = 0;
}

arr2.push(obj);
console.log(arr2);

Output:

[{
 left: 0,
 top: 0
}]

In our code above, we started with two arrays: arr1, containing keys (left and top), and arr2, an empty array we wanted to populate with key-value pairs. We then created an empty object called obj to store the key-value pairs before pushing them into arr2.

Using a for loop, we iterated through the elements in arr1, which occurred twice, once for left and once for top. Within the loop, we utilized bracket notation (obj[key]) to assign a value of 0 to each key in the obj object, effectively creating key-value pairs.

Once the loop was completed, we had an object obj with the desired key-value pairs. We then pushed this obj object into arr2 using the push() method.

Finally, we logged arr2 to the console, displaying the array containing our key-value pairs.

Now, let’s move to built-in functions and methods to push key-value pairs into arr2.

Use map() to Push Key-Value Pair Into an Array in JavaScript

ECMAScript 6 (ES6) introduced arrow functions, a concise way to write functions, particularly when the function has only one statement. This feature enhances code efficiency and readability, streamlining function syntax using the => operator.

Arrow functions prove especially useful when used with methods like map() in JavaScript.

The map() method makes a new array by calling a function once for every array’s element. It does not modify the original array, and it runs for empty elements.

In the JavaScript code snippet below, we can see the map() method in action. This method is invoked on an array named arr1, which contains the initial values left and top.

An arrow function is used to transform each element of arr1 into an object where the original element serves as a property with a value of 0. This transformation results in a new array named arr2, which holds objects with the properties left and top, each initialized to 0.

JavaScript Code:

var arr1 = ['left', 'top'];
const arr2 = arr1.map(value => ({[value]: 0}));
console.log(arr2);

Output:

[{
 left: 0
}, {
 top: 0
}]

In the output, we can see that the map() method effectively creates distinct objects with the same data but different properties. In this case, each object has a single property based on the values obtained from the original array, showcasing the versatility and usefulness of the map() method when combined with arrow functions in modern JavaScript development.

Use reduce() to Push Key-Value Pair Into an Array in JavaScript

The reduce() method in JavaScript is a powerful tool for processing arrays, allowing the execution of a reducer function that ultimately yields a single accumulated value as a result.

Similar to the map() method, reduce() doesn’t modify the original array, even when encountering empty elements within the array. Let’s see a practical example to illustrate this.

JavaScript Code:

var arr1 = ['left', 'top'];
const arr2 = arr1.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
console.log(arr2);

Output:

{
  left: 0,
  top: 0
}

Once again, we began with arr1, which contained keys (left and top). Our goal was to create an object arr2 with key-value pairs.

To achieve this, we employed the reduce() method on arr1, iterating over its elements and accumulating a single result, in this case, an object.

Within the reduce() method, a callback function was provided. This function had two parameters: obj (the accumulator) and arrValue (the current element in the array).

In this callback function, we set obj[arrValue] to 0, effectively creating a key-value pair in the obj object. The key was the current element from arr1, and the value was 0.

As we progressed, the reduce() method accumulated these key-value pairs in the obj object.

Finally, we logged arr2 to the console, presenting the object with the desired key-value pairs.

Use jQuery to Push Key-Value Pair Into an Array in JavaScript

Let’s say you’re aiming to structure a key-value pair within an array based on two properties (left and top) from an object. We’ll demonstrate how to achieve this using jQuery.

Example Code:

var arr1 = ['left', 'top'], arr2 = [];
var obj = {};

$.each(arr1, function(index, value) {
  obj[value] = 0;
});

arr2.push(obj);
console.log(arr2);

Output:

[{
 left: 0,
 top: 0
}]

In this example, we used jQuery’s $.each() function to achieve the same result. We started with arr1, which contained keys (left and top).

Recall that our goal was to create an array arr2 with objects where each key from arr1 mapped to a value of 0. To accomplish this, we initialized an empty object obj to store our key-value pairs.

Next, we utilized $.each() to iterate over the elements in arr1. Inside the callback function, index represented the index of the element, and value was the current element.

For each element in arr1, we created a key-value pair in the obj object, where the key was the current element (value) and the value was 0.

Once the loop was completed, we proceeded to push the obj object into arr2 using the push() method. Finally, we logged arr2 to the console, presenting an array containing our key-value pairs.

Now, if you have two arrays and you want to pair all elements from both arrays into a third array, you can achieve this by using a loop or JavaScript’s built-in methods.

Here’s how you can do it:

var keys = ['ID', 'FirstName', 'LastName', 'Gender'],
    values = [1, 'Mehvish', 'Ashiq', 'Female'], arr = [];
var obj = {};

for (i = 0; i < keys.length && i < values.length; i++) {
  obj[keys[i]] = values[i];
}
arr.push(obj);
console.log(arr);

Output:

[{
  ID: 1,
  FirstName: 'Mehvish',
  LastName: 'Ashiq',
  Gender: 'Female'
}]

Here, we started with two arrays: keys and values. To capture the resulting objects, we also initialized an empty array arr, which was intended to hold one or more objects, each representing a set of key-value pairs.

Additionally, we set up an empty object ‘obj’ to store the key-value pairs for each iteration of the loop.

Using a for loop, we iterated through the elements of both keys and values. This loop proceeded as long as i was less than the length of both arrays.

Within the loop, we accessed elements from both keys and values using the current value of i. This allowed us to create a key-value pair in the obj object, with the key taken from the keys array and the value extracted from the values array.

The loop continued until it had processed all elements present in both arrays, generating key-value pairs for each pair of elements in the two arrays.

Once the loop concluded, we had an obj object containing all the key-value pairs.

We utilized the push() method to add the obj object to the arr array. This action effectively inserted the object into the array as a single element.

Finally, we logged the arr array to the console, presenting an array that held a single object with all the desired key-value pairs.

Conclusion

JavaScript offers multiple ways to incorporate key-value pairs into arrays, each catering to distinct programming needs and preferences. From fundamental iterations using for loops and manual object creation to leveraging modern constructs like map() and reduce(), developers can select the most appropriate method based on context and efficiency requirements.

Additionally, we explored how jQuery simplifies this process using its $.each() function. Armed with this knowledge, you can now effectively manage and organize data within arrays, enhancing your JavaScript programming capabilities.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Array