JSON content is basically represented as an associative array in JavaScript. You just need to loop over them to either read the key or the value:

    var JSON_Obj = { "one":1, "two":2, "three":3, "four":4, "five":5 };

    // Read key
    for (var key in JSON_Obj) {
       console.log(key);
       console.log(JSON_Obj[key]);
   }
Answer from Anand on Stack Overflow
🌐
EyeHunts
tutorial.eyehunts.com › home › how to get key and value from json array object in javascript | example code
How to get key and value from JSON array object in JavaScript | Code
August 22, 2022 - Just use for-loop over them to either read the key or the value. <script> var JSON_Obj = { "one":1, "two":2, "three":3, "four":4, "five":5 }; // Read key for (var key in JSON_Obj) { console.log(key); console.log(JSON_Obj[key]); } </script>
Top answer
1 of 6
48

JSON content is basically represented as an associative array in JavaScript. You just need to loop over them to either read the key or the value:

    var JSON_Obj = { "one":1, "two":2, "three":3, "four":4, "five":5 };

    // Read key
    for (var key in JSON_Obj) {
       console.log(key);
       console.log(JSON_Obj[key]);
   }
2 of 6
19

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.)

Here, length of this array is 2.

No, it's 3.

So, i need to get the name (like amount or job... totally four name) and also to count how many names are there?

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 use for..in:

var entry;
var name;
entry = array[0];
for (name in entry) {
    // here, `name` will be "amount", "job", "month", then "year" (in no defined order)
}

Full working example:

(function() {
  
  var array = [
    {
      amount: 12185,
      job: "GAPA",
      month: "JANUARY",
      year: "2010"
    },
    {
      amount: 147421,
      job: "GAPA",
      month: "MAY",
      year: "2010"
    },
    {
      amount: 2347,
      job: "GAPA",
      month: "AUGUST",
      year: "2010"
    }
  ];
  
  var entry;
  var name;
  var count;
  
  entry = array[0];
  
  display("Keys for entry 0:");
  count = 0;
  for (name in entry) {
    display(name);
    ++count;
  }
  display("Total enumerable keys: " + count);

  // === Basic utility functions
  
  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
  }
  
})();
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Since you're dealing with raw objects, the above for..in loop is fine (unless someone has committed the sin of mucking about with Object.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 a hasOwnProperty call in there:

for (name in entry) {
  if (entry.hasOwnProperty(name)) {
    display(name);
    ++count;
  }
}
Discussions

jquery - How can I get the key name and its value from an array within a JSON object - Stack Overflow
My Problem In my JSON file I have an object within an object with a value which is an array of key/value pairs. I am having trouble outputting each key name and its value. My Code menu.json {"t... More on stackoverflow.com
🌐 stackoverflow.com
Obtaining key, value from $.each - json OBJECT; NOT array
🌐 forum.jquery.com
Extract specific values from key/value
I have a json object like: { "hrMl": [ { "key": "mlHr", "data": 1, }, { "key": "mlHr", "data": 2, }, { "key": "mlHr", "data": 2, }, ] } I’m wondering how I can extract data where it equals 2 and put to an array and 1 into an array? So the result will be two new arrays: TArray = [2,2] OArray ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
6
0
June 1, 2021
javascript - Loop and get key/value pair for JSON array using jQuery - Stack Overflow
I'm looking to loop through a JSON array and display the key and value. It should be a simplified version of the following post, but I don't seem to have the syntax correct: jQuery 'each' loop w... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 4
154

There are two ways to access properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

For a more complex example, let's assume you have an array of objects that represent users:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

Another example: obj[2].key[3]["some key"]

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.


As Amadan noted, it might be worth also discussing how to loop over different structures.

To loop over an array, you can use a simple for loop:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

2 of 4
21

Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below:

var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'

var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];
🌐
YouTube
youtube.com › hey delphi
How to get key and value from json array object in javascript? - YouTube
How to get key and value from json array object in javascript?A little intro about me, Hi, my name is Delphi, nice to meet you. Let me help you with your que...
Published: July 1, 2023
Views: 7
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-get-a-value-from-a-json-array-in-javascript
How to Get a Value from a JSON Array in JavaScript? - GeeksforGeeks
June 28, 2025 - To retrieve a value from a JSON array in JavaScript, we can use various methods such as accessing the array by index or using built-in methods like find(), map(), etc. In a JSON array, values are stored in an ordered list, which means you can ...
🌐
Infinitbility
infinitbility.com › how-to-get-key-and-value-from-json-object-in-javascript
How to get key and value from JSON object in javascript
September 9, 2021 - Disclaimer: References to any specific company, product or services on this Site are not controlled by GoDaddy.com LLC and do not constitute or imply its association with or endorsement of third party advertisers
🌐
Pointerunits
pointerunits.com › 2012 › 03 › getting-keyvalue-pair-from-json-object.html
Getting key/value pair from JSON object and getting variable name and value from JavaScript object.
March 28, 2012 - Using for-each loop I got all the key value from jsonObj, and finally using that key I got the corresponding value. Finally I got the alert like this, Key: a value:10 Key: b value:20 Key: c value:30 Key: d value:50 During this workaround I got one more idea, using this same way I got all the ...
Find elsewhere
🌐
Quora
quora.com › How-can-I-extract-and-change-key-JSON-Array-of-Objects-in-JavaScript
How to extract and change key JSON Array of Objects in JavaScript - Quora
Answer (1 of 3): Well here’s how to do it as requested: [code]// initial data var books = { "History": [ {"Number": "AD-3424"}, {"Number": "AD-3424"} ] }; // changing the array at books.History using Array.prototype.map books.History = books.History.map(function(book) { return {"...
🌐
Thequantizer
thequantizer.com › the quantizer › javascript
JavaScript: How to Get JSON value by Key :: The Quantizer
let firstKey = Object.keys(firstObj)[0]; let firstKeyValue = firstObj[firstKey]; //to print it out console.log("price of first object is: " + firstObj[firstKey]); ... If we wanted preform operations on all the elements in the array we have a few ways to do this.
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Extract specific values from key/value - Curriculum Help - The freeCodeCamp Forum
June 1, 2021 - I have a json object like: { "hrMl": [ { "key": "mlHr", "data": 1, }, { "key": "mlHr", "data": 2, }, { "key": "mlHr", "data": 2, }, ] } I’m wondering how I can extract data where it equals 2 and put to an array and 1 into an array? So the result will be two new arrays: TArray = [2,2] OArray ...
🌐
IQCode
iqcode.com › code › javascript › javascript-get-json-keys
javascript get json keys Code Example
October 9, 2021 - Object.keys(jsonData).forEach(function(key) { var value = jsonData[key]; // ... }); ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond. Sign up · Develop soft skills on BrainApps Complete the IQ Test ... how to get keys of a json object in javascript ...
Top answer
1 of 3
291
var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];

for(var i in jsonData){
    var key = i;
    var val = jsonData[i];
    for(var j in val){
        var sub_key = j;
        var sub_val = val[j];
        console.log(sub_key);
    }
}

EDIT

var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj);  // returns ["person", "age"]

Object has a property keys, returns an Array of keys from that Object

Chrome, FF & Safari supports Object.keys

2 of 3
138

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

🌐
ServiceNow Community
servicenow.com › community › developer-forum › parse-json-array-to-get-key-value-pair › m-p › 2469890
Archived - ServiceNow Community
February 6, 2023 - Some PDIs are currently unavailable, and PDI actions are paused. View the latest updates here. Read More · This Content was Archived
🌐
TutorialsPoint
tutorialspoint.com › article › get-value-for-key-from-nested-json-object-in-javascript
Get value for key from nested JSON object in JavaScript
March 15, 2026 - // Example JSON object const data = { "name": "John", "age": 30, "address": { "street": "421 Main Street", "city": "Anytown", "state": "CA" } }; // Function to access nested properties using string paths function getNestedValue(obj, path) { // Handle direct property access if (path in obj) { return obj[path]; } // Split path by dots and traverse const keys = path.split("."); let value = obj; for (let i = 0; i < keys.length; i++) { value = value[keys[i]]; if (value === undefined) { break; } } return value; } // Using the function to access nested values const name = getNestedValue(data, "name"); const age = getNestedValue(data, "age"); const street = getNestedValue(data, "address.street"); const state = getNestedValue(data, "address.state"); console.log("Name:", name); console.log("Age:", age); console.log("Street:", street); console.log("State:", state);