arraysjsonfor-looparraylist

how to access each json object in a array using for loop?


{
  "item1" : [{"index":"1"},{"id":"1","name":"npm","result":"expected text1"},{"id":"2","name":"yarn","result":"expected text2"},{"id":"3","name":"pnpm","result":"expected text3"}],
  "item2":  [{"index":"2"},{"id":"1","name":"npm","result":"expected text1 for item2"},{"id":"2","name":"yarn","result":"expected text2 for item 2"},{"id":"3","name":"pnpm","result":"expected text3 for item 2"}]

}

I want to access item1 and item2 using for loop? how can I do it?


Solution

  • const data = {
      "item1": [
        { "index": "1" },
        { "id": "1", "name": "npm", "result": "expected text1" },
        { "id": "2", "name": "yarn", "result": "expected text2" },
        { "id": "3", "name": "pnpm", "result": "expected text3" }
      ],
      "item2": [
        { "index": "2" },
        { "id": "1", "name": "npm", "result": "expected text1 for item2" },
        { "id": "2", "name": "yarn", "result": "expected text2 for item 2" },
        { "id": "3", "name": "pnpm", "result": "expected text3 for item 2" }
      ]
    };
    
    for (const key in data) {
      for (const obj of data[key]) {
        console.log(obj);
      }
    }