This question already has an answer here:
这个问题已经有了答案:
- Access / process (nested) objects, arrays or JSON 18 answers
- 访问/处理(嵌套)对象、数组或JSON 18答案
Get guys,
的家伙,
I've tried looking through a bunch of tutorials but I can't seem to find one that covers this in detail. Maybe somebody could point me int he right direction.
我已经试着看了很多教程,但是我似乎找不到一个能够详细介绍这些内容的教程。也许有人能给我指明正确的方向。
I have a .json file that looks like this:
我有一个。json文件是这样的:
{
"users": [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Sabrina",
"lastName": "Doe"
}]
}
I want to run a .each loop and grab all of the users. Here's what I've tried:
我想运行一个。each循环并获取所有的用户。这是我试过:
$.getJSON("database.json", function(data) {
$.each(data.users, function(key, val) {
$('.dbUL').append('<li>' + key + ' : ' + val + '</li>');
});
});
So it looks like it actually does spit out the array since I get an output of 0 : [object Object] and 1 : [object Object].
看起来它确实输出了数组因为我得到了0:[object]和1:[object]的输出。
My question is, how do I dig into the array and actually spit out the objects that I have stored in my array?
我的问题是,如何对数组进行深入挖掘,并将我存储在数组中的对象全部吐出来?
2 个解决方案
#1
4
Knowing the properties what you want get (fistName, lastName
): jsBin
知道要获取的属性(fistName, lastName): jsBin
$.getJSON("database.json", function(data) {
$.each(data.users, function(idx, val) {
$('.dbUL').append('<li>' + val.firstName + ' : ' + val.lastName + '</li>');
});
});
Not knowing the properties you want to get: jsBin
不知道要获取的属性:jsBin
$.getJSON("database.json", function(data) {
var LIhtml = "";
$.each(data.users, function(idx, obj) {
LIhtml += "<li>";
for(var key in obj){
if(obj.hasOwnProperty(key)){
LIhtml += obj[key]+" ";
}
}
LIhtml += '</li>';
});
$('.dbUL').append(LIhtml);
});
#2
1
As far as I know there isn't a fancy way to grab the values of a "Hash" in JS like you do in Ruby, for example.
就我所知,没有一种方法可以像在Ruby中那样使用JS中“散列”的值。
Why not just using something like this below?
为什么不使用下面这样的东西呢?
$('.dbUL').append('<li>' + key + ' : ' + val.firstName + ' ' + val.lastName + '</li>');
#1
4
Knowing the properties what you want get (fistName, lastName
): jsBin
知道要获取的属性(fistName, lastName): jsBin
$.getJSON("database.json", function(data) {
$.each(data.users, function(idx, val) {
$('.dbUL').append('<li>' + val.firstName + ' : ' + val.lastName + '</li>');
});
});
Not knowing the properties you want to get: jsBin
不知道要获取的属性:jsBin
$.getJSON("database.json", function(data) {
var LIhtml = "";
$.each(data.users, function(idx, obj) {
LIhtml += "<li>";
for(var key in obj){
if(obj.hasOwnProperty(key)){
LIhtml += obj[key]+" ";
}
}
LIhtml += '</li>';
});
$('.dbUL').append(LIhtml);
});
#2
1
As far as I know there isn't a fancy way to grab the values of a "Hash" in JS like you do in Ruby, for example.
就我所知,没有一种方法可以像在Ruby中那样使用JS中“散列”的值。
Why not just using something like this below?
为什么不使用下面这样的东西呢?
$('.dbUL').append('<li>' + key + ' : ' + val.firstName + ' ' + val.lastName + '</li>');