Get JSON Value from Key

Why is undefined getting logged?

var arr = [{"eat" : 0}, {"sleep" : 1}, {"code" : 2}];
var key = "eat";
console.log(arr[key]);

I expect to see 0 in the log.

http://jsfiddle.net/jFFW5/

Answers


First, I don't see any JSON here. I see a plain JavaScript array object - JSON is a data serialization format.

Second, you're probably looking for arr[0] which would return {"eat": 0}.

Arrays are used for storing sequential data.

Alternatively, you can store them in an object if that fits what you actually wanted:

var arr = {"eat" : 0,"sleep" : 1,"code" : 2};
var key = "eat";
console.log(arr[key]);

Note: in more modern implementations - you should probably use a Map instead of an array for that. Or use Object.create(null)


You've got an array with three properties. Their names are "0", "1", and "2". Those names are derived implicitly from the fact that three values (three object literals) are listed in the array literal.

In order to find an entry in the array with a property "eat", you'll have to iterate through the array.


It's not JSON, it's an array of single item JSON objects.

You could get 0 like this:

console.log(arr[0][key]);

But it would be better to have an actual JSON object that you could use in the way you want. That would look something like {"eat" : 0, "sleep" : 1, "code" : 2} (just remove the []s and internal {}s. If you do this your arr[key] will work as expected... although arr might not be the best name for a JSON object :)


function convertThatArrayToAnObject(arrayOfObjects) {
  var returnObject = {}
  for (var i = 0; i < arrayOfObjects.length; i++) {
    var key = Object.keys(arrayOfObjects[i])[0]
    returnObject[key] = arrayOfObjects[i][key] 
  }
  return returnObject
}

Need Your Help

Qt object signals are not connected to methods(handlers)

c++ qt qgraphicsscene

I'm faced with a problem to handle clicks in Qt. I have the following class:

Checking from shell script if a directory contains files

bash unix shell

From a shell script, how do I check if a directory contains files?