0

i have a json array

var a_values = new Array();
a_values["AF:All"] = new Array('KBL:Kabul','US:New york');
a_values["AL:All"] = new Array('TIA:Tirana');

How can i find , whether a given string is in a_values, using jquery

for example, i need to check whether 'Kabul' is there , in a_values

1

2 Answers 2

1

I think you'd like this a little better:

var abbreviations = new Array();
abbreviations['AF'] = new Array();
abbreviations['AF']['KBL'] = 'Kabul';
abbreviations['AF']['US'] = 'New York';
abbreviations['AL'] = new Array();
abbreviations['AL']['TIA'] = 'Tirana';

Then there are two ways of checking for existence of a string. One would be:

JSON.stringify(abbreviations).indexOf('Kabul') >= 0

And another would be to loop through the array with a for loop, looking at each value.

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

2 Comments

But the problem is that, the array is a predefined result from another location
I see. That's fine, you can still stringify it with the method I showed. The loop would be a little nastier but you could do it that way too. If you're actually getting a JSON string btw, you can just do indexOf
1

That's not JSON at all, that's just Javascript. JSON is a text format for representing objects, based on parts of the Javascript syntax.

You are creating an array, but then you are using it as a regular object. (The reason that it works anyway, is that an array is also an object.) You should create an object instead:

var a_values = {};

To look for a value in the object, you can loop through it's properties:

var find = 'Kabul';
var found = false;
$.each(a_values, function(key, value){
  if (value.indexOf(find) != -1) {
    found = true;
    return false; // skip rest of the loop
  }
});

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.