How to Push Both Key and Value into an Array in jQuery

This is a simple way method to work with Array of Objects, You can simply push values to append it to an array, But if the array is Array of Object means you have to be careful on implementing the append operation.  In this article I am going to show you , how to deal with the Array of Objects and its pushing values for Object Property and its Value.

Lets start with a simple array example, Here I have an Array of Objects, We are going to store it on another array .

var first_array = [{ index: 5, name: 'Varadha' },{ index: 2, name: 'Karthi' },{ index: 3, name: 'Kvcodes'},{ index: 4, name: 'blog'}]; 
var second_array = new Array();  // Empty array for our use.

Now, We are going to copy first array values to second array , Here we are going to use push method to copy Index and name both things.

$.each(first_array, function (index, value) {
      second_array.push({name: value.name,  index:  value.index});
}); // Here I just Interchanged the location of the objects.

If you want to Print this array of objects, you need each function to print it. Here I just showed you the sample code to jQuery Alert it one by one.

$.each(second_array, function (index, value) {
    alert({"name: "+value.name +" and index: "+ value.index});
}); // Here I just Interchanged the location of the objects.

From the above code results like this result.

name: Varadha and index : 5

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

One comment

Comment Below

Your email address will not be published. Required fields are marked *


Current ye@r *



Subscribe E-mail Updates

Subscribe to our email newsletter.



Category Posts