JavaScript - 枚举嵌套对象结构

时间:2012-01-15 15:06:38

标签: javascript

我需要帮助解析这个对象:

var user = {
    "10000068485": {"id":"10000068485","name":"Jenan"},
    "10000099257": {"id":"10000099257","name":"John"}
}

我需要阅读每行的idname属性:

1 row - id = 10000068485 and name = Jenan
2 row - id = 10000099257 and name = John

到目前为止我已经尝试过了:

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
       }
     }
   }
}

评论:“我想在一行中显示ID和名称。”

评论:“在html表格中。”

评论:“我想将ID和名称分为两列。”

4 个答案:

答案 0 :(得分:2)

您有2个键(ID),每个键都有两个键(idname)。所以在你非常内循环中,它是4(= 2 x 2)。

> for(key in user) {
...   obj = user[key];
...   for (prop in obj) {
...      console.log(obj[prop])
...   }
... }
10000068485
Jenan
10000099257
John

答案 1 :(得分:1)

如果您的HTML表格是这样的话......

<table id=data_table>
    <thead>
        <th>ID</th>
        <th>NAME</th>
    </thead>
    <tbody>
    </tbody>
</table>

你可以这样插入......

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/


这是一个在div中创建新元素的示例。

结果结构如下:

<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 ) );
   }
}

DEMO: http://jsfiddle.net/qtcTS/2/

答案 2 :(得分:0)

你应该这样做

for (var key in user) {
     var obj = user[key];
    if (obj.hasOwnProperty("name") && obj.hasOwnProperty("id")) {
        alert("id:"+obj.id +" & name:"+obj.name);
   }
}

小提琴:http://jsfiddle.net/TQEND/2/

答案 3 :(得分:0)

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);
    }
}