Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to modify a json array with jQuery

Tags:

json

jquery

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!

like image 241
Subliminal Hash Avatar asked May 18 '10 21:05

Subliminal Hash


3 Answers

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.

like image 112
Tomalak Avatar answered Nov 11 '22 00:11

Tomalak


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;
 }
}
like image 30
Jhonny D. Cano -Leftware- Avatar answered Nov 11 '22 02:11

Jhonny D. Cano -Leftware-


Try this:

for (var i = 0; i < groups.length; i++){
 if (groups[i].gid == 28){ 
     groups[i].ishidden = true;
     break;
 }
}
like image 8
Justin Ethier Avatar answered Nov 11 '22 00:11

Justin Ethier