uzzum07
uzzum07

Reputation: 101

how to loop through an array of objects and access the properties inside each array to display in an html element?

I have a JSON response shown below :

rows: Array(2)
0:
ID: "35"
datedCreated: "2019-10-19 22:34:34"
text: "rferfrefrf"
userid: "1"
__proto__: Object
1:
ID: "36"
datedCreated: "2019-10-20 04:50:45"
text: "fesfsefsfdsdfsdfsdfdsfdsfsdfsdf sdfsdfsdfs"
userid: "2"
__proto__: Object
length: 2
__proto__: Array(0)
__proto__: Object

What I am trying to do is access the data within each object and have it displayed as a an html element like a div. In this case I would have 2 divs displayed on my html form. However if i returned 15 object I would like 15 divs each the different information of the objects. I know I am supposed to loop through the objects and I know I can do that using with the index but if I want the information divs to display automatically I think I would need to do a nested loop? One that loops through the number of objects and then another one where I create the div element and supply it with the information from the object.. right? so far I have this.

for (var i = 0; i < data.rows.length; i++) {
for (var key in data.rows[i]) {
    for (var j = 0; j < data.rows[i][key].length; j++) {
        console.log(data.rows[i][key][j])
    }
}

}

And I get the first object

3
5
2
0
1
 9
 -
1
0
-
1
9
 ---- 
2
:
3
4
:
3
4
1
r
f

but I know I'm not doing it correctly. but essentially i would need this concept where it shows me the values for each object in the array. I know how to create the div i am just struggling with this

Upvotes: 0

Views: 64

Answers (1)

hifebriansyah
hifebriansyah

Reputation: 341

you can use 'recursion' to achieve your goal. hopefully the link bellow can help you

looping through an object (tree) recursively

and try to run snippet, hopefully in can help you in some ways.

var obj = {
  a1: '',
  a2: {
    b1: '',
    b2: {
      c1: '',
      c2: {
        d1: '',
      },
      c3: {
        d2: '',
      }
    },
    b3: '',
    b4: '',
    b5: '',
  },
  a3: ''
}

function eachRecursive(obj, text, dash) {
  temp = ''

  for (var k in obj) {
    temp += '<div>' + ('-'.repeat(dash)) + ' ' + k + '</div>';
    
    if (typeof obj[k] == "object" && obj[k] !== null) {
      dash1 = dash + 1;
      temp += eachRecursive(obj[k], text, dash1);
    }
  }

  return text + temp
}

document.write(eachRecursive(obj, '', 1));

Upvotes: 1

Related Questions