0

I need to find a value based on another object value

json = {[{ID:"1",city:"Atlanta"},{ID:"2",city:"New York"}]}

and so forth.

I need to find the value of a city where ID is x. Is there anyway to do it without using loops?

More Details: I have to create a json object looping thru the document, then I send this json to the webservice, which return me another set of json to populate the fields.

3
  • 1
    Are there other properties, or is changing the JSON an option? Commented Aug 18, 2010 at 19:37
  • 3
    Why do you need to do this without using loops? is this thing massive? Also, are all id's guaranteed to be there? E.g. if you have something of id 5, is there guaranteed to be ids of 1-4. Lastly, are these things always in order? Meaning that the array comes pre-sorted by id? Commented Aug 18, 2010 at 19:37
  • Edited for more details. Commented Aug 18, 2010 at 19:50

3 Answers 3

3

You could format it as follows

var data = {
    id: "city",
    1: "Atlanta",
    2: "New York",
    6: "New Jersy",
    24: "San Diego"
};

At which point, access can be done using the ID and the array access operator

console.log(data[2], data[24]);

yields

New York San Diego

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

Comments

1

You could consider using JSONPath, JSONQuery, jLinq, etc... although under-the-hood there's a very good chance they will use loops.

Comments

0

Why don't you store this like an array

array = ["Atlanta", "New York"];

Calling array[0] will return "Atlanta".

If you have to use json you will need to use loops to do what you want.

1 Comment

This assumes that the ID's are in order, sequential, and start at 0.

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.