admin管理员组文章数量:1308458
I like to know how i can get first specific value in a json like
$.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
I like to know how i can get first specific value in a json like
$.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
Share
Improve this question
asked Jan 23, 2014 at 2:07
jttoratejttorate
611 gold badge1 silver badge9 bronze badges
4
-
1
What data type is
data
? Object or array – scrblnrd3 Commented Jan 23, 2014 at 2:09 - If it's not an Array, then there is no "first" since objects are unordered. – cookie monster Commented Jan 23, 2014 at 2:10
-
You may be able to get the first that is defined in the original JSON string if you use
JSON.parse()
and pass it a "reviver" function. I think it'll give you the properties you encounter in order, though it'll traverse into a nested object before giving you the key for that object. – cookie monster Commented Jan 23, 2014 at 2:18 -
...other than that, if all you need is the first property of the object, then you could parse it yourself just up to that point, and then
JSON.parse()
it, and use the property you found to grab the first., – cookie monster Commented Jan 23, 2014 at 2:22
3 Answers
Reset to default 5If data
is an array, you can do
name=data[0].name
If it's an object, it's slightly more plicated
name=data[Object.keys(data)[0]].name;
Keep in mind that object keys aren't really sorted in any particular order
It depends on the structure of the json object but it should look like this:
data[0].name
If you return false
from the iteration function, $.each()
terminates the loop. So you can simply return false
the first time:
$.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.
本文标签: How to get first specific value in json object using javascriptStack Overflow
版权声明:本文标题:How to get first specific value in json object using javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741862381a2401700.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论