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

JSON response parsing in Javascript to get key/value pair - Stack Overflow
How can I get the name and value of each object in Javascript only? More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
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 {"...
🌐
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
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"];
🌐
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 ...
🌐
ServiceNow Community
servicenow.com › community › developer-forum › parse-json-array-to-get-key-value-pair › m-p › 2469890
Solved: parse json array to get key value pair - ServiceNow Community
February 7, 2023 - It looks like that mrvs is already a json object, you don't need to use JSON.parse(mrvs) to convert it to a json object. Try to such as use mrvs[0] .name to get the name... Have a try ! Please mark my answer as correct and helpful based on Impact. ... var gr = new GlideRecord('incident'); gr.addQuery('number', 'INC0001164'); gr.query(); if (gr.next()) { var mrvs = gr.variables.employee_details; var Payload = JSON.parse(mrvs); for (var i = 0; i < Payload.length; i++) { var obj = Payload[i]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; j++) { var key = keys[j]; if (key == "name") { gs.print("Name: " + obj[key]); } if (key == "manager") { gs.print("Manager: " + obj[key]); } } } }
Find elsewhere
🌐
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 - Suddenly I wondered whether it's possible or not, after that I had done lot of workaround and finally got this solution. See the below example. function getKeyValueFromJSON() { ... In this example I have created the one json array as string, and converted this string into JSON object using ...
🌐
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 = [1] Here is a jsfiddle of what I am trying to do.
🌐
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.
🌐
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);
Top answer
1 of 2
2

you can use Object.keys to get an array of all of your object's keys. Once you have that array, you can use Array.forEach to iterate over it as necessary:

Object.keys(usersObject).forEach(function(key, keyIndex) {
  console.log("index:",keyIndex,"key:",key,"value:",usersObject[key]);
});

But!

your particular problem here is being caused by using $.map instead of JSON.parse. $.map returns an array, so of course your keys are always going to be numerical array indices - 0, 1, 2, and so on. You're not going to be able to use hash keys to find things in the array returned by $.map. Furthermore, judging by your variable names you're calling $.map on a string which is definitely not going to do what you want. Assuming you figure that part out and you somehow get a valid JavaScript object, and you still need to use $.map() for some reason, what you can do is this:

// $.map will return an array...
$.map(user_profiles_object, function(objVal, objKey) {
    // ...and each item in that array will be an object with a
    // property named 'key' and a property named 'val'
    return {
      key: objKey,
      val: objVal
    };
}).forEach(function(arrayObj) {
    // now each item in the array created above will be an object
    // created by your callback function:
    console.log(arrayObj.key,":",arrayObj.val);
});
2 of 2
0

You can also rely on Js's foreach.

// JSON string must be valid. Enclose your JSON in '{}' (curly braces);
var user_profiles_string =  '{ "users": { "key_11": { "text": "11" }, "key_22": { "text": "22" }, "key_33": { "text": "33" }}}';
var user_profiles_array  = JSON.parse(user_profiles_string); 

// For retrieval in loop, the Js foreach asigns the key to index param (i in this case).
for (i in user_profiles_array.users) {
    // i is the key of the user currently iterated.
    console.log('Key name is: ' + i);
    // Use i as the index to retrieve array value.
    console.log(user_profiles_array.users[i]);
}

// For direct retrieval using any given known key:
console.log(user_profiles_array.users['key_11']);
🌐
Kii Cloud
docs.kii.com › en › guides › cloudsdk › javascript › managing-data › json-document › get-key-value
Getting a Key-value Pair
// Get a value of a JSON object. var jsonObject = object.get("myObject"); console.log(JSON.stringify(jsonObject)); // Get a value of a JSON array.
Top answer
1 of 3
292
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
139

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