1

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
CodeSlave
  • 457
  • 6
  • 17
  • 2
    There are no arrays in jQuery, and in javascript there are no associative arrays ? – adeneo Dec 20 '13 at 12:27
  • possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) –  Dec 20 '13 at 12:33
  • It seems that you confuse ids and indexes. Firstly, read the question above to find the object with the corresponding id, then update the object like this : `foundObject.status = false`. –  Dec 20 '13 at 12:37
  • This answer is fine : http://stackoverflow.com/a/7364184/1636522. `findById(id_status, id).status = false`. –  Dec 20 '13 at 12:41

3 Answers3

1
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
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

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/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497