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?
Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).
The json auto operator automatically detects where the JSON object is located and parses it.
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
}
}
Use a for..in
loop:
for( x in response.groupIds[i]) {
// x is now your unknown key
// response.groupIds[i][x] is the unknown value
}
Since there is only one property of the object, that'll work nicely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With