简体   繁体   中英

Updating jquery associative array values

I am trying to update values of an array but I am getting null instead. Here is how I populate the array:

   var id_status = []; id_status.push({ id:1, status: "true" });

So basically I end creating a JSON object with this array but how do I update individual values by looping through the array? Here is what I am attempting to do:

var id = $(this).attr("id"); id_status[id] = "false";

I want to be able to access the item in the array and update its' status after getting the row id.

var id_status = {};  // start with an objects

id_status['1'] = {status: true }; // use keys, and set values

var id = this.id;  // assuming it returns 1

id_status[id].status = false; // access with the key

This function will either update an existing status or add a new object with the appropriate status and id.

var id_status = []; 
id_status.push({ id:1, status: true }); //using actual boolean here
setStatus(1, false);
setStatus(2, true);

//print for testing in Firefox
for(var x = 0; x < id_status.length; x++){
    console.log(id_status[x]);
} 

function setStatus(id, status){
    //[].filter only supported in modern browsers may need to shim for ie < 9
    var matches = id_status.filter(function(e){
       return e.id == id;
    });
    if(matches.length){
        for(var i = 0; i < matches.length; i++){
           matches[i].status = status; //setting the status property on the object
        } 
    }else{
        id_status.push({id:id, status:status});
    }
}

JS Fiddle: http://jsfiddle.net/rE939/

If the id is going to be unique, make id_status an object like this

var id_status = {};
id_status[1] = "true";   //Boolean value in String?!?

Access it with the id directly to get the status

console.log(id_status[1]);

Since, objects are like hashtable, accessing the elements will be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM