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

Congrats, You are Subscribed to Receive Updates.

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
commenter

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.

3 comments

  1. commenter

    hi, can you please help me in resolving my query issue please?

    I want to create a 2-dimensional array with the following format:
    myArray = [ keyName: keyValue, valueName: valueValue ]

    here is the bit of my snippet:

    var buttonArray = [“string 1”, “string 2”, “string 3”];

    for (i=0; i < buttonArray.length; i++) {
    stringTest = encodeURI([buttonArray[i]]);
    recNumber = i + 1;

    if ( stringTest != '' ) {
    myArray.push([{"recomNum":recommendationNumber}, {"recomString":stringTest}]);
    }

    };

Comment Below

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

*

Current ye@r *

Menu

Sidebar

Subscribe E-mail Updates

Congrats, You are Subscribed to Receive Updates.

Advertisement

Category Posts