我有一个Json对象,基本上是一个数组,在每个数组中我想迭代属性,所以我做了这样的事情:
for(var x = 0;x<dados.feeds.length;x++){
for(var y in dados.feeds[x]){
console.log(dados.feeds[x][y]);
/*if(data == dataInicial){
console.log("a");
}*/
}
}
console.log(dados.feeds[x][0]
)给了我undefined,我只想要每个x行的第一个元素,我怎么能得到它?
json object dados
{
"channel":
{
"id": 9,
"name": "my_house",
"description": "Netduino Plus connected to sensors around the house",
"latitude": "40.44",
"longitude": "-79.996",
"field1": "Light",
"field2": "Outside Temperature",
"created_at": "2010-12-13T20:20:06-05:00",
"updated_at": "2014-02-26T12:43:04-05:00",
"last_entry_id": 6060625
},
"feeds":
[
{
"created_at": "2014-02-26T12:42:49-05:00",
"entry_id": 6060624,
"field1": "188",
"field2": "25.902335456475583"
},
{
"created_at": "2014-02-26T12:43:04-05:00",
"entry_id": 6060625,
"field1": "164",
"field2": "25.222929936305732"
}
]
}
答案 0 :(得分:0)
您的数据如何?如果它与
类似var dados = {
feeds: [ {a: 'aa'}, {b: 'bb'} ]
}
然后你可以试试这个:
dados.feeds.forEach(feed => {
Object.keys(feed).forEach((key, index) => {
if(index === 0) { console.log(feed[key]) } // aa bb...
})
})
HTH
答案 1 :(得分:0)
应为console.log(dados.feeds[x].created_at);
。
答案 2 :(得分:0)
虽然you shouldn't rely on Javascript object key order,但这是一个解决方案,它将返回feeds数组中每个条目中第一个键的值;
var dados = {
"channel":
{
"id": 9,
"name": "my_house",
"description": "Netduino Plus connected to sensors around the house",
"latitude": "40.44",
"longitude": "-79.996",
"field1": "Light",
"field2": "Outside Temperature",
"created_at": "2010-12-13T20:20:06-05:00",
"updated_at": "2014-02-26T12:43:04-05:00",
"last_entry_id": 6060625
},
"feeds":
[
{
"created_at": "2014-02-26T12:42:49-05:00",
"entry_id": 6060624,
"field1": "188",
"field2": "25.902335456475583"
},
{
"created_at": "2014-02-26T12:43:04-05:00",
"entry_id": 6060625,
"field1": "164",
"field2": "25.222929936305732"
}
]
};
var con = document.getElementById('console');
for (var i = 0; i < dados.feeds.length; i++) {
var firstKey = Object.keys(dados.feeds[i])[0];
con.innerHTML += '<p>' + dados.feeds[i][firstKey] + '</p>';
}
/*
Prints;
2014-02-26T12:42:49-05:00
2014-02-26T12:43:04-05:00
*/
Here是工作代码的小提琴。
答案 3 :(得分:0)
你拥有它的代码运行良好,一切都没有出现,没有任何未定义(我试过)。
但是,console.log [x] [0]将跟踪undefined,因为:
var x = 0;
var obj = feeds[x]; // this will be the first object from the feeds array.
console.log ( obj [ 0 ] );
你现在可能已经看到了;将跟踪undefined,因为该obj没有0属性。它是具有键/值的对象。
所以这会奏效:
var each = 'created_at';
console.log ( obj [ each ] );
而且:
for ( var each in obj ) {
console.log ( each, obj [ each ] );
}