-1

I have a json like this:

var json = {
  "A": {
    "A1": {
      "A11": "A",
      "A12": "B",
      "A13": "C"
    },
    "A2": {
      "A21": "A",
      "A22": "B",
      "A23": "C"
    }
  },
  "B": {
    "B1": {
      "B11": "A",
      "B12": "B",
      "B13": "C"
    },
    "B2": {
      "B21": "A",
      "B22": "B",
      "B23": "C"
    }
  }
}

I can access it using:

json.B.B13

But I want to loop through all objects. (A, B) how can I do this?

tought about using for(...) and: json[0].B13 but that doesn't work.

How can I do it?

  • 1
    `Object.entries(json).forEach(([k, v]) => cosole.log(k, v))` – ulou Jun 11 '21 at 12:33
  • 4
    This is not JSON. This is a JavaScript object. – phuzi Jun 11 '21 at 12:33
  • You can create a recursive function and process the keys and values based on your requirement: `function process(o) { for(const k in o) { console.log(k, o[k]); if(typeof o[k] === 'object') process(o[k]) } }` – adiga Jun 11 '21 at 12:37
  • Thanks. It indeed is a json object out of visual studio. – DominikReber Jun 11 '21 at 12:40
  • @phusi yeah and `JSON` is abbreviation of `JavaScript Object Notation`. – ulou Jun 11 '21 at 12:40
  • 1
    @ulou `var json =` is not allowed in JSON. The right side of the assignment is a JavaScript object, not JSON data. JSON data is a text/string. You would have to `JSON.parse` JSON data to use it in JavaScript. –  Jun 11 '21 at 12:45
  • 1
    The only _"json object"_ in JavaScript is [JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) and it's not what you think. –  Jun 11 '21 at 12:48
  • @jabaa Your comment kinda makes no sens, `var = json` is `object`/`string` declaration not `JSON` itself. If OP would named it `parsedJson` instead of `json` everything would ok, but let's leave this pointless discussion. – ulou Jun 11 '21 at 12:50
  • 1
    @ulou My point is that phuzi is right. There is no JSON in this question. There is a JavaScript code that contains a section that would be valid JSON. `var json = JSON.parse('{}')` contains two characters of JSON data. `var json = {}` doesn't contain JSON. –  Jun 11 '21 at 12:52

1 Answers1

0

You can use recursion, console.log only if value isn't object, otherwise repeat:

const json = {A:{A1:{A11:"A",A12:"B",A13:"C"},A2:{A21:"A",A22:"B",A23:"C"}},B:{B1:{B11:"A",B12:"B",B13:"C"},B2:{B21:"A",B22:"B",B23:"C"}}};

const deepIterate = ([k, v]) => {
  if (typeof v === 'object' && v !== null)
    Object.entries(v).forEach(deepIterate)
  else
    console.log(k, v)
}

Object.entries(json).forEach(deepIterate)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */
ulou
  • 5,542
  • 5
  • 37
  • 47