0

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
4
  • 1
    What data type is data? Object or array Commented Jan 23, 2014 at 2:09
  • If it's not an Array, then there is no "first" since objects are unordered. 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. 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., Commented Jan 23, 2014 at 2:22

3 Answers 3

5

If data is an array, you can do

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

Sign up to request clarification or add additional context in comments.

7 Comments

The Object.keys approach won't guarantee any particular item as the "first" item. ... "...object keys aren't really sorted except for the order you put it in." No, there is no order. The order you give guarantees nothing.
@cookiemonster I thought that if you put three properties in an object like obj={foo:"bar",baz:"qux"}, this will give foo first
@scrblnrd3: No, there are no guarantees as to the order. That goes for for-in as well as Object.keys. Different browsers may behave differently. The same browser may even behave differently in different situations.
Could you give an example please?
It's specified partially here sec-12.6.4 -- "The mechanics and order of enumerating the properties is not specified" -- and probably somewhere else.
|
1

It depends on the structure of the json object but it should look like this:

data[0].name

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.