Ad

Read And Display Array Nested Values

- 1 answer

I have to display the tab values in a list with heading and subheading. I can read the object keys count but failed to get the values of each node and child values.

Please advise on how to retrieve the values and display in HTML

enter image description here

var tab= {
  "a": {
    "one": [
      {
        "name": "xxx",
        "age": "10"
      } 
    ],
    "two": [
      {
        "name": "yxss",
        "age": "11"
      }
    ]
  },
  "b": {
    "one": [
      {
        "name": "ctr",
        "age": "11"
      },
      {
        "name": "cft",
        "age": "11"
      }
    ]
  },
  "c": {
    "two": [
      {
        "name": "cccc",
        "age": "11"
      }
    ]
  }
}

let count = Object.keys(tab).length;
console.log(count);
for (i =0; i < count ; i ++)
{ 
  console.log("<h1>"+tab[i]+"</h1>");
  let count1 = Object.values(tab[i]).length;
    for (j =0; j < count1 ; j++)
    { 
      console.log(tab[i][j]);

    }
}

Ad

Answer

Is it good for you?

var tab= {
  "a": {
    "one": [
      {
        "name": "xxx",
        "age": "10"
      } 
    ],
    "two": [
      {
        "name": "yxss",
        "age": "11"
      }
    ]
  },
  "b": {
    "one": [
      {
        "name": "ctr",
        "age": "11"
      },
      {
        "name": "cft",
        "age": "11"
      }
    ]
  },
  "c": {
    "two": [
      {
        "name": "cccc",
        "age": "11"
      }
    ]
  }
}

$(document).ready(function() {
  Object.keys(tab).forEach(function(k) {
    $('#result').append('<h1>' + k + '</h1>')
      Object.keys(tab[k]).forEach(function(kk) {
        $('#result').append('<ul id= "' + kk + '">' + kk + '</ul>')
        tab[k][kk].forEach(function(i) {
          $('#'+kk).append('<li>' + i.name  + '</li>')
        })
      })
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="result"></div>

Ad
source: stackoverflow.com
Ad