JavaScript - enumerating a nested object structure [closed]
-
16-04-2021 - |
Question
I need help with parsing this object:
var user = {
"10000068485": {"id":"10000068485","name":"Jenan"},
"10000099257": {"id":"10000099257","name":"John"}
}
I need to read the id
and name
properties of each row:
1 row - id = 10000068485 and name = Jenan
2 row - id = 10000099257 and name = John
I've tried this so far:
for (var key in user) {
if (user.hasOwnProperty(key)) {
var obj = user[key];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
//This read 4 rows and no 2 rows
}
}
}
}
comment: "I want to show id and name in one line."
comment: "In an html table."
comment: "I want to put the id and the name into two columns."
Solution
If your HTML table is this...
<table id=data_table>
<thead>
<th>ID</th>
<th>NAME</th>
</thead>
<tbody>
</tbody>
</table>
You could insert like this...
var user = {
"10000068485": {"id":"10000068485","name":"Jenan"},
"10000099257": {"id":"10000099257","name":"John"}
};
var tbody = document.getElementById('data_table').tBodies[0];
for (var key in user) {
if (user.hasOwnProperty(key)) {
var row = tbody.insertRow( tbody.rows.length );
row.insertCell( 0 )
.appendChild( document.createTextNode( user[key].id ) );
row.insertCell( 1 )
.appendChild( document.createTextNode( user[key].name ) );
}
}
DEMO: http://jsfiddle.net/qtcTS/1/
Here's an example that creates new elements in a div.
The resulting structure will look like:
<div id=main>
<p>
<span>10000068485</span> <span>Jenan</span>
</p>
<p>
<span>10000099257</span> <span>John</span>
</p>
</div>
JS
var user = {
"10000068485": {"id":"10000068485","name":"Jenan"},
"10000099257": {"id":"10000099257","name":"John"}
};
var p, main = document.getElementById('main');
for (var key in user) {
if (user.hasOwnProperty(key)) {
p = main.appendChild( document.createElement('p') );
p.appendChild( document.createElement('span') )
.appendChild( document.createTextNode( user[key].id ) );
p.appendChild( document.createElement('span') )
.appendChild( document.createTextNode( user[key].name ) );
}
}
OTHER TIPS
You have 2 keys (the ids) with each of them having two keys (id
, name
). So in you very inner loop, it's 4 (= 2 x 2).
> for(key in user) {
... obj = user[key];
... for (prop in obj) {
... console.log(obj[prop])
... }
... }
10000068485
Jenan
10000099257
John
you should do it like this
for (var key in user) {
var obj = user[key];
if (obj.hasOwnProperty("name") && obj.hasOwnProperty("id")) {
alert("id:"+obj.id +" & name:"+obj.name);
}
}
fiddle : http://jsfiddle.net/TQEND/2/
for (var key in user) {
if (user.hasOwnProperty(key)) {
var obj = user[key];
var row = { };
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
row[prop] = obj[prop];
}
}
// at this stage the row variable will contain the id and name properties
// row = { id: '10000068485', name: 'Jenan' }
console.log(row);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow