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.

4
  • 2
    There are no arrays in jQuery, and in javascript there are no associative arrays ? Commented Dec 20, 2013 at 12:27
  • possible duplicate of Find object by id in array of javascript objects Commented Dec 20, 2013 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. Commented Dec 20, 2013 at 12:37
  • This answer is fine : stackoverflow.com/a/7364184/1636522. findById(id_status, id).status = false. Commented Dec 20, 2013 at 12:41

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.