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

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.


If you know exactly the nesting level of your value, then a quick solution (as suggested in other answers) is possible.

However, if you need a deep traversal search, you're gonna need a recursive version of the solutions, something like:

function FindTraverse(data, match)
{
    for (var prop in data)
    {
         if (!data.hasOwnProperty(prop)) continue;
         if (data[prop] == match) return true;
         if (typeof data[prop] == 'object' && FindTraverse(data[prop], match)) return true;
    }

    return false;
}

Examples:

FindTraverse({a:'Foo',b:'Bar'}, 'Bar') // true
FindTraverse(['Foo','Bar'], 'Bar') // true
FindTraverse([{name:'Foo'},{name:'Bar'}], 'Bar') // true
FindTraverse({a:{name:'FooBar'},b:'Bar'}, 'FooBar') // true

However, if you're looking for a more thorough solution, use a framework like jsTraverse


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;
  };
}
链接地址: http://www.djcxy.com/p/18970.html

上一篇: 是不是写传统上空的不良习惯的元素自闭标签?

下一篇: 如何检查字典中的特定字符串?