javascript 如何使用javascript获取json对象中的第一个特定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21297984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get first specific value in json object using javascript
提问by jttorate
I like to know how i can get first specific value in a json like
我想知道如何在 json 中获得第一个特定值,例如
$.each(data, function(i, val){
console.log(val.name);
});
sample output of above code is like this
上面代码的示例输出是这样的
John
Mary
Kite
but i like to get only first value like this
但我喜欢只得到这样的第一个值
John
回答by scrblnrd3
If data
is an array, you can do
如果data
是一个数组,你可以做
name=data[0].name
If it's an object, it's slightly more complicated
如果是对象,稍微复杂一些
name=data[Object.keys(data)[0]].name;
Keep in mind that object keys aren't really sorted in any particular order
请记住,对象键实际上并没有按任何特定顺序排序
回答by vooD
It depends on the structure of the json object but it should look like this:
这取决于 json 对象的结构,但它应该如下所示:
data[0].name
回答by Barmar
If you return false
from the iteration function, $.each()
terminates the loop. So you can simply return false
the first time:
如果false
从迭代函数返回,则$.each()
终止循环。所以你可以简单地false
第一次返回:
$.each(data, function(i, val){
console.log(val.name);
return false;
});
Since object elements don't have any inherent order, there's no guarantee this will print a specific name. It will just pick one of the names arbitrarily.
由于对象元素没有任何固有顺序,因此不能保证这将打印特定名称。它只会任意选择其中一个名称。