0

I have an API endpoint that returns some data in the below format.

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
}

I thought it would be relatively trivial to be able to iterate through each key-value pair in this JSON payload, but I seem to be having errors with it. The code I have below is what I am using to first parse the JSON from string format into a variable, then I want to iterate through each key in the JSON object, retrieve the key and value, and then do something with both of those values.

var dictionary = JSON.parse(data);

for (var key in dictionary) {
    var identifier = key;
    var identifierValue = dictionary[key];

    //do stuff..

I'm not sure whether the for() is valid in this instance, how exactly can I iterate through each key-value pair in the JSON object?

My issue is that I can't seem to access they keys or values held in the dictionary variable. It seems as though the for loop isn't working, which makes me feel like it's invalid for this use case. If this was C# I'd have to do something similar to

for(var key in dictionary.keySet)
{
    //do...
}

I'm looking for the equivalent in JS.

  • Assuming that's an object (although it's not clear from the format you've posted the data in the question) there's several methods you can use to iterate through its properties: https://stackoverflow.com/questions/8312459/iterate-through-object-properties. If you can edit the question to show a more accurate example of the response data we can give you a more accurate answer. – Rory McCrossan Mar 27 '19 at 10:57
  • 4
    What is the error? Provide a [mcve] – Prerak Sola Mar 27 '19 at 10:58
  • I prefer `Object.entries().forEach()` over `for ... in` or one of its siblings `Object.keys()` and `Object.values()`. It allows you to pretend the object is an array without having to do the mapping of `dictionary[key]` manually. – Shilly Mar 27 '19 at 10:59
  • Please add more information. What, if any, are the errors logged in the console? What type is the data variable? If it is an object, JSON.parse throws a SyntaxError. – jro Mar 27 '19 at 11:41

5 Answers5

0

The code you posted looks oke, however there are alternative ways to iterate over an object:

Object.keys(jsonObject)
  .forEach(function eachKey(key) { 
    alert(key); // alerts key 
    alert(jsonObject[key]); // alerts value
  });
SaWo
  • 1,515
  • 2
  • 14
  • 32
  • [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Mar 27 '19 at 16:48
0

Your approach is just fine. You iterate dictionary, it will store the key in var key.

To access the value of this iterated array, you just access the array with the key.

for (var key in dictionary) {
    if (dictionary.hasOwnProperty(key)) {
         var value = dictionary[key]
         console.log(key + '=>' + value);
    }
}
Nick
  • 565
  • 4
  • 19
0

Your own code seems alright. No idea why it throws an error from the code shown.

The Object.entries() example I commented about goes as follows:

const data_json = '{"key1":"value1","key2":"value2","key3": "value3"}';
const dictionary = JSON.parse( data_json );
Object.entries( dictionary ).forEach(([ key, value ]) => {
  console.log( `found key ${ key } with value ${ value }` );
});
Shilly
  • 8,511
  • 1
  • 18
  • 24
0

It seems you want to know some other ways of doing that. There can be other ways

Object.entries and forEach()

let obj = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

Object.entries(obj).forEach(([key, value]) => {
  console.log(key);
  console.log(value)
})

Object.keys and forEach()

let obj = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

Object.keys(obj).forEach(key => {
  console.log(key);
  console.log(obj[key])
})
adiga
  • 34,372
  • 9
  • 61
  • 83
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

If your API data are surrounding by a quotation, then you need to use JSON.parse before run an iterator.

var data = '{"key1": "BMW", "key2": "Volvo", "key3": "Saab", "key4": "Ford"}';

var cars = JSON.parse(data);

Object.keys(cars).forEach(function(key) {
    console.log(key + "=" + cars[key]);
});

And if data are plain object, no need to use JSON.parse.

var cars = {"key1": "BMW", "key2": "Volvo", "key3": "Saab", "key4": "Ford"};

Object.keys(cars).forEach(function(key) {
    console.log(key + "=" + cars[key]);
});
Mahfuzur Rahman
  • 1,497
  • 18
  • 23