Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for specific string in a dictionary?

I have a dictionary like:

a = {"staticData":['----','Blue','Green'], "inData":['Indatahere','----','----']}

How can I find that if the dictionary contains "----", in any of the key's values.
Any Javascript function?
EDIT: What if the case is like this?

a = {"staticData":[], "inData":['Indatahere','----','----']}

It's giving this Error:

TypeError: a[elem].indexOf is not a function
like image 700
MHS Avatar asked Jul 10 '13 10:07

MHS


2 Answers

Here is the code:

var a = {"staticData":['----','Blue','Green'], "inData":['Indatahere','----','----']};

for(var key in a){
    var value = a[key];
    for(var i=0; i<value.length; i++){
        if(value[i] == '----') alert("Found '----' in '" + key + "' at index " + i);
    };
}

EDIT: Changed iteration over array to normal way after comment.

like image 78
ElmoVanKielmo Avatar answered Sep 20 '22 14:09

ElmoVanKielmo


Use indexOf to search each array in the a object:

for (elem in a)
{
    if (a[elem].indexOf("----") != -1)
       alert('---- found at ' + a[elem]);
}

EDIT For this error: TypeError: a[elem].indexOf is not a function the browser possibly considers an empty element to be a non-string type; non-string type does not have an indexOf method.

This code checks the length of the array element (if the element is empty before interpreting the indexOf function.

for (elem in a)
{
    if (a[elem].length > 0 && a[elem].indexOf("----") != -1)
       alert('---- found at ' + a[elem]);
}

If you wish to support IE < 9, see this post to conditionally add a indexOf definition to the Array object. The post also mentions a Jquery alternative.

The SO post mentioned above lists this Mozilla version of indexOf function.

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
like image 32
suspectus Avatar answered Sep 20 '22 14:09

suspectus