how to modify a json array with jQuery

17,586

Solution 1

I would say the Justin answer is better, however, I would add this subtle modification

var lim = groups.length;
for (var i = 0; i < lim; i++){
 if (groups[i].gid == 28){ 
     groups[i].ishidden = true;
     break;
 }
}

Solution 2

jQuery style would be:

$(groups).each( function() {
  if (this.gid == 28) this.ishidden = true;
});

But alternatively you can create an index:

var index = {};
$(groups).each( function() { index[this.gid] = this; } );

// and then
index["28"].ishidden = true;

This would save some time in the long run.

Solution 3

Try this:

for (var i = 0; i < groups.length; i++){
 if (groups[i].gid == 28){ 
     groups[i].ishidden = true;
     break;
 }
}
Share:
17,586
SykoTron
Author by

SykoTron

Updated on July 06, 2022

Comments

  • SykoTron
    SykoTron almost 2 years

    I have the following json array of objects in my code

    var groups = [
    { "gid": 28, "name": "Group 1", "ishidden": false, "isprivate": false },
    { "gid": 16, "name": "Group 2", "ishidden": true, "isprivate": false },
    { "gid": 31, "name": "Group 3", "ishidden": true, "isprivate": false },
    { "gid": 11, "name": "Group 4", "ishidden": false, "isprivate": false },
    { "gid": 23, "name": "Group 5", "ishidden": false, "isprivate": false }
    ];
    

    I can access or iterate through this with no problm using jQuery. However a situation arose where I need to change a value of one of the items (e.g. change the ishidden property to true for gid: 28) and then run some other jQuery function against it. Is this possible? or do I have to re-build the whole object ? If possible, how can I achieve this?

    any help would be appreciated!

  • Alec
    Alec about 14 years
    +1. How can you not like jQuery with syntax as simple as this? :)
  • SykoTron
    SykoTron about 14 years
    I actually tested all answers and they all worked.. I chose this one as it is the first answer to my question. otherwise all the answers work perfectly.
  • SykoTron
    SykoTron about 14 years
    I come across to articles / tips all over the place suggesting not to use $.each where ever possible (mainly for large information) as it is slower than native javascript. but your second alternative is quite interesting in a way that I have not come accross any example similar to this one. I would like to learn more about it. Can you give some information on it? or provide resources may be? thank you very much for the answer too!
  • Tomalak
    Tomalak about 14 years
    @Emin: Regarding: $.each() is slower than the alternative (i.e.: a native loop): Yes, that's true. Will it be so slow that it matters in comparison? Probably not, but you have to benchmark for yourself. Modern JS engines are blazingly fast, and unless you have several thousands of records to loop over, you will hardly notice any difference. Regarding the alternative solution: Happy to explain. What exactly don't you understand?