Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  74] [ 1]  / answers: 1 / hits: 18794  / 12 Years ago, thu, march 15, 2012, 12:00:00

Here is my response code in jQuery:



var response = $.parseJSON(response);

for (var i = 0; i < response.groupIds.length; i++) {
console.log(response.groupIds[i], i);
}


Each response.groupIds[i] is of the form {unknown name:unknown value}.



I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?


More From » json

 Answers
97

Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.



var group = response.groupIds[i];

var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
var name = allPropertyNames[j];
var value = group[name];
// Do something
}


Your question's response format contains only one key-value pair. The code can then be reduced to:



var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list; = key name
var value = group[name];


If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.



for (var name in group) {
if (group.hasOwnProperty(name)) {
var value = group[name];
// Do something
}
}

[#86817] Wednesday, March 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;