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.