CodeSlave
CodeSlave

Reputation: 457

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.

Upvotes: 1

Views: 1191

Answers (3)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

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/

Upvotes: 0

adeneo
adeneo

Reputation: 318212

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

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239473

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.

Upvotes: 0

Related Questions