How do I get the key value in a JSON object and the length of the object using JavaScript?
For example:
[
{
"amount": " 12185",
"job": "GAPA",
"month": "JANUARY",
"year": "2010"
},
{
"amount": "147421",
"job": "GAPA",
"month": "MAY",
"year": "2010"
},
{
"amount": "2347",
"job": "GAPA",
"month": "AUGUST",
"year": "2010"
}
]
Here, length of this array is 3. For getting, value is fine ([0].amount), in index[0] it has three name value pairs.
So, I need to get the name (like amount or job… totally four name) and also how do I count how many names there are?
First off, you’re not dealing with a “JSON object.” You’re dealing with a JavaScript object. JSON is a textual notation, but if your example code works (
[0].amount), you’ve already deserialized that notation into a JavaScript object graph. (What you’ve quoted isn’t valid JSON at all; in JSON, the keys must be in double quotes. What you’ve quoted is a JavaScript object literal, which is a superset of JSON.)No, it’s 3.
If you’re using an environment that has full ECMAScript5 support, you can use
Object.keys(spec | MDN) to get the enumerable keys for one of the objects as an array. If not (or if you just want to loop through them rather than getting an array of them), you can usefor..in:Full working example:
Since you’re dealing with raw objects, the above
for..inloop is fine (unless someone has committed the sin of mucking about withObject.prototype, but let’s assume not). But if the object you want the keys from may also inherit enumerable properties from its prototype, you can restrict the loop to only the object’s own keys (and not the keys of its prototype) by adding ahasOwnPropertycall in there: