user3521579 user3521579 - 5 months ago 12
JSON Question

How to compare the data in JSON object to a variable?

Hi guys so I was wondering if it was possible to search content in a Json object with a variable?

Example:

var username = "name";


The json object Im getting from an api is in the following format:

{"name":{"id":224463,"name":"name","profileIconId":715,"revisionDate":1465905397000}}


The username is obviously different for everyone. I want to be able to get the id of the user and display it when the user enters their username in a text field.

HTTP.get(url,function(error,result){
var username ="somename";
console.log(result.username.id);

});


That code above gives me undefined but if I put somename where username is then it works fine.

Answer

Use bracket notation to access property using a variable

console.log(result[username].id)
//               -^-      -^-