Use JSON2.js

var obj = JSON.parse(data);
for(var key in obj){
    if (obj.hasOwnProperty(key)){
        var value=obj[key];
        // work with key and value
    }
}
Answer from Shiplu Mokaddim on Stack Overflow
Top answer
1 of 4
10

Use for-in...something like:

for (var i in dictionary) {
    dictionary[i].forEach(function(elem, index) {
        console.log(elem, index);
    });
}

where the i would iterate through your dictionary object, and then you can use forEach for every json array in the dictionary(using dictionary[i])

With this code you'll get

Object {id: "0", name: "ABC"} 0 
Object {id: "1", name: "DEF"} 1 
Object {id: "0", name: "PQR"} 0 
Object {id: "1", name: "xyz"} 1 

You can tailor the forEach function definition(replacing the console.log bit) to do whatever you want with it.

DEMO

Edit: Doing the same thing using Object.keys

Object.keys(dictionary).forEach(function(key) {
    dictionary[key].forEach(function(elem, index) {
        console.log(elem, index);
    });
});

Edit2: Given the somewhat complicated structure of your jsonData object, you could try using a (sort of) all-purpose function that would act on each type of component separately. I've probably missed a few cases, but maybe something like:

function strung(arg) {
    var ret = '';
    if (arg instanceof Array) {
        arg.forEach(function(elem, index) {
            ret += strung(elem) + ',';
        });
    } else if (arg instanceof Object) {
        Object.keys(arg).forEach(function(key) {
            ret += key + ': /' + strung(arg[key]) + '/';
        });
    } else if (typeof arg === "string" || typeof arg === "number") {
        ret = arg;
    }
    return ret;
}

document.body.innerHTML = strung(jsonData);

DEMO

2 of 4
1

Please note that yours is just a JavaScript array object. To make it simple to understand, you can iterate over it like this:

for (var i in dictionary) {
    // do something with i
    // here i will contain the dates

    for (n = 0; n < dictionary[i].length; n++) {
        // do something with the inner array of your objects    
        // dictionary[i][n].id contains the "id" of nth object in the object i
        // dictionary[i][n].name contains the "name" of nth object in the object i
    }
}

See this fiddle: http://jsfiddle.net/Ke8F5/

The iteration looks like this:

12Jan2013 : (id = 0, name = ABC) (id = 1, name = DEF)  
13Jan2013 : (id = 0, name = PQR) (id = 1, name = XYZ)
Discussions

javascript - how to loop through a nested dictionary or json data in Reactjs - Stack Overflow
Using Reactjs how do you create a function component that loop through the json data below and display location content. I want the function to also be able to display something else like members if More on stackoverflow.com
🌐 stackoverflow.com
json - Loop through data to create a dictionary with key/value pairs using JavaScript - Stack Overflow
I'm trying to modify some Javascript code to create objects from each row and assign these objects their corresponding key/value pairs. I have not been able to figure this out. My spreadsheet look... More on stackoverflow.com
🌐 stackoverflow.com
February 3, 2020
Iterate through dictionaries in javascript and access values? - Stack Overflow
I am not a javascript expert, so I am sure what I am trying to do is pretty straight forward, but, here it is: I have an array that comes down from a database, it looks like this: [{"name":"aName"," More on stackoverflow.com
🌐 stackoverflow.com
javascript - Trying to loop through JSON file - Stack Overflow
I am creating a dictionary app in React, I have loaded in the JSON dictionary which looks like this: { "DIPLOBLASTIC": "Characterizing the ovum when it has two primary germinallayers.", "DEFIGURE"... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Coderwall
coderwall.com › p › _kakfa › javascript-iterate-through-object-keys-and-values
JavaScript iterate through object keys and values (Example)
June 26, 2023 - In ES6, the Object.keys() method was added to make iterating through objects simpler. Two new methods, Object.entries() and Object.values, were later introduced to ES8 (). The most recent methods arrayize the object before iterating across the array using array looping techniques. Let's start with the first approach! ... When retrieving several key-value pairs from an object in JavaScript, you might need to cycle across the object.
Top answer
1 of 2
1

Of course that I cant make an entire project solution for you but the function that you wanted must have this kind of logic.

const jsonData = [{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "authorization": "Black card",
      "location": [
        "Next",
        "Previous",
        "Here"
      ]
    }
  ]
}]

jsonData.forEach(item=>{
  
  item.members.map((member)=>{
    
    if(member.location&&member.location[0]){
  
      //Do whatever, maybe you want to use return statement in there
      console.log(member.location)
    }
    else{
    
      //do something else, or add more conditions
      console.log("There's no location in it")
    }
  })
})

you can put it in a variable and add your variable inside your jsx return statement or use it directly in middle of your function's return statement.

Good luck.

2 of 2
1

You can map through data in a functional component the same way you would map through a class component. For this example, you could list only nested data:

const List = () => {
  return (
    <div>
      {data.map(item =>
        (item.members || []).map(member =>
          (member.location || []).map(item => (<div>{item}</div>))
        )
      )}
    </div>
  );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

which would list only the nested "location" data for each member if that property exists. Or you could map through data and display top-level properties and then also map through its nested properties:

const List = () => {
  return (
    <div>
      {data.map(item => (
        ((item.members || []).map(member => (
          <div>
            {member.name || ''}
            {member.location && member.location.map(loc => (<div>{loc}</div>))}
          </div>
        )))
      ))}
    </div>
  );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

🌐
SitePoint
sitepoint.com › blog › javascript › how to loop through a json response in javascript
How to Loop Through a JSON Response in JavaScript — SitePoint
February 15, 2024 - If the property value is an object (i.e., a nested JSON object), the inner loop iterates over each property in the nested object. Converting a JavaScript object into a JSON string can be done using the JSON.stringify() method.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-json-object-in-javascript
How to Iterate JSON Object in JavaScript? - GeeksforGeeks
July 23, 2025 - Inside the forEach loop, each property value can be accessed using obj[key] ... const obj = { "company": 'GeeksforGeeks', "contact": '+91-9876543210', "city": 'Noida' }; Object.keys(obj).forEach(key => { console.log(`${key}: ${obj[key]}`); }); ...
Top answer
1 of 1
1
  • You want to convert the following Spreadsheet values as follows.

    • From

      Persons name    surname profession
      Sally   Sally   Smith   Developer
      John    John    Appleseed   Accountant
      
    • To

      {
        "ID Sally": {"name": "Sally", "surname": "Smith", "profession": "Developer"},
        "ID John": {"name": "John", "surname": "Appleseed", "profession": "Accountant"}
      }
      
  • You want to achieve this using Node.js.

  • You have already been able to get the values from Spreadsheet.

    • The values of sheetData in your script is as follows.

      [
        ["Persons","name","surname","profession"],
        ["ID Sally","Sally","Smith","Developer"],
        ["ID John","John","Appleseed","Accountant"]
      ]
      

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Sample script:

var sheetData = [["Persons","name","surname","profession"],["ID Sally","Sally","Smith","Developer"],["ID John","John","Appleseed","Accountant"]];

// Sample script for converting the values from Spreadsheet to a dictionary.
var header = sheetData.shift();
header.shift();
var dictionary = sheetData.reduce(function(obj1, row) {
  var value = row.shift();
    obj1[value] = header.reduce(function(obj2, f, j) {
    obj2[f] = row[j];
    return obj2;
  }, {});
  return obj1;
}, {});
console.log(dictionary);


// Write each dictionary to its own es6 module file
let personArray = [];
for (const person in dictionary) {
    let output = `export const ${person} = {\n`;
    for (const key in dictionary[person]) {
        const value = dictionary[person][key];
        if (value && isNaN(value)) {
            output += `    {value}",\n`;
        } else if (!isNaN(value) && value !== "") {
            output += `    {value},\n`;
        } else {
            output += `    ${key}: undefined,\n`;
        }
    }
    output += `};\n\n`;
    personArray.push(output);
}
console.log(personArray);

  • In above sample script, dictionary can be used for dictionary in your script.

If I misunderstood your question and this was not the result you want, I apologize. At that time, can you provide the sample input and output values you expect? By this, I would like to modify it.

Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 42087730 › trying-to-loop-through-json-file
javascript - Trying to loop through JSON file - Stack Overflow
// compare function which needs to be added somewhere function compareTerm(term, compareTo) { var shortenedCompareTo = compareTo .split('') .slice(0, term.length) .join(''); return term.indexOf(shortenedCompareTo.toLowerCase()) === 0; } // only changed the compare function handleSearch: function(term) { var results = []; for (var key in Dictionary) { if (Dictionary.hasOwnProperty(key)) { if (compareTerm(term, Dictionary[key])) { results.push(Dictionary[key]) } } } console.log(results); },
🌐
Stack Overflow
stackoverflow.com › questions › 55906162 › looping-through-json-in-jquery
Looping through json in jQuery - Stack Overflow
... There's nothing really to iterate ... in case that one's not right. It's all been covered thoroughly. ... You can use the jQuery $.each() function to loop over your data....
🌐
Microverse
microverse.org › home › blog › how to loop through the array of json objects in javascript
How to Loop Through the Array of JSON Objects in JavaScript
September 29, 2022 - This tutorial will guide you on how to loop the array of JSON objects in JavaScript. We’ll explain the types of loops and how to use them.
🌐
Stack Overflow
stackoverflow.com › questions › 18238173 › javascript-loop-through-json-array
JavaScript loop through JSON array? - Stack Overflow
I am trying to loop through the following json array: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": &...
🌐
Gitbooks
buzzcoder.gitbooks.io › codecraft-javascript › content › object › iterate-over-a-dictionary.html
Iterate Over a Dictionary · CodeCraft - JavaScript - BuzzCoder
To iterate over all properties in an object, we can use the loop for...in... to iterate over the keys: · Here in the for loop, variable k receives the keys of object fruits ('apple', 'pear'...). Then fruits[k] is used to access the value paired with the key k
🌐
Medium
allaboutcode.medium.com › top-3-ways-to-loop-through-a-json-object-in-javascript-67ca21d33a24
Top 3 Ways to Loop Through a JSON Object in JavaScript | by Marika Lam | Medium
September 27, 2022 - const res = JSON.parse(xhr.responseText);Object.entries(res).forEach((entry) => { const [key, value] = entry; console.log(`${key}: ${value}`); });// id: SvzIBAQS0Dd // joke: What did the pirate say on his 80th birthday?
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript loop through dictionary
How to Loop Through Dictionary in JavaScript | Delft Stack
March 13, 2025 - One of the simplest ways to loop through a dictionary in JavaScript is by using the for...in loop.
🌐
Futurestud.io
futurestud.io › tutorials › iterate-through-an-objects-keys-and-values-in-javascript-or-node-js
Iterate Through an Object’s Keys and Values in JavaScript or Node.js
March 3, 2022 - Object.keys(tutorials).forEach(key => { console.log(`${key}: ${tutorials[value]}`) }) // nodejs: 123 // android: 87 // java: 14 // json: 7 · The for…in loop exists in JavaScript for a long time. It was already supported in Internet Explorer 6.
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript loop through json object
JavaScript loop through JSON object
March 15, 2023 - Simple example code for…in loop iterates over all enumerable properties of an object: Inside the loop, we use template literals to print the key-value pairs to the console. <!DOCTYPE html> <html> <body> <script > const data = { "name": "John", ...
🌐
ZetCode
zetcode.com › javascript › jsonforeach
JavaScript JSON forEach - Iterating Over JSON Arrays
The fetch function retrieves data as JSON array from the provided URL. With forEach, we go through the array.