Get JSON Value from Key

Why is undefined getting logged?

var arr = [{"eat" : 0}, {"sleep" : 1}, {"code" : 2}];
var key = "eat";

I expect to see 0 in the log.


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";

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

Need Your Help

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.