views:

48

answers:

3

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.

+1  A: 

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

STW
A: 

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.

Daniel Moura
This assumes that the ID's are in order, sequential, and start at 0.
Justin Johnson
+1  A: 

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

Justin Johnson