In some cases, developers need to add the key-value pairs in an array, with the help of JavaScript libraries, such as “jQuery”. Developers prefer to use an array instead of a typical object to take advantage of the indexing and iteration features of an array while still having access to the data via a key.
This blog will describe the procedure to push the key-value pairs in an array using jQuery.
How to Push/Add Both Key and Value Into an Array Using jQuery?
To push the key-value pairs in an array, use the jQuery “each()” method with the “push()” method. The “each()” method is one of the most used traversal methods in jQuery. It takes a callback function as a parameter that is triggered for every element. While the “push()” method is utilized for adding elements in an array.
Syntax
Following syntax is used for the jQuery “each()” method:
For adding elements in an array, utilize the given syntax:
Note: For pushing key-value pairs in an array in jQuery, use the “push()” method inside the callback function.
To use the jQuery “each()” method for adding key-value pairs in an array, first, you need to add a jQuery library in the <head> tag using the “src” attribute of the <script> element:
Example
Here, in the given example, first, we will create an object that contains three key-value pairs:
"id": "3",
"name": "Jack",
"age": 28
}
Then, create an empty array where we will push the key-value pairs:
Call the “each()” method to iterate the object “obj” using the callback function, where we will first create a new object literal called “element”. Then, set the “key” as a property of an element, and the value as the value of that property. Lastly, we will call the “push()” method to add the element into an empty array:
var element= {};
element[key] = value;
array.push(element);
});
Finally, print the array on the console using the “console.log()” method:
As you can see, the key-value pairs have been successfully added into an empty array using the jQuery:
That was all about pushing both key and value into an array in jQuery.
Conclusion
To push the key-value pairs in an array, use the jQuery “each()” method with the “push()” method. The “each()” method is one of the most used traversal methods in jQuery. The “push()” method is used inside the callback function of the “each()” method to add elements to an array. This blog described the procedure to push the key-value pairs in an array using jQuery.