0

Trying to run the following code

var superGroup = $.parseJSON(data);
$.each(superGroup, function(idx, obj) {
            if (idx.contains("Addr_Line")) {
                if (obj != null) {
                    currentAddress.push(obj);
                }
            }
        });

Where supergroup is a JSON object with a bunch of properties and I basically only want to add the values of the properties in this object which contain "addr_line". In chrome I noticed there is a JS error on

idx.contains()

Saying idx does not contain a method contains

Any idea how I can get around this ?

3
  • 1
    In this case, idx will either be a string or a number. Neither of which have a .contains() method. EDIT: String.contains() exists, but nothing (except Firefox) supports it. Commented Jan 28, 2014 at 20:33
  • When I did a alert(idx), it showed all the property names of my object i.e id,blah,Address_Line_1,Address_Line_2, etc the code seemed to work in firefox but chrome didnt like it Commented Jan 28, 2014 at 20:35
  • You could have easily answered this question yourself by reading the docs. Commented Jan 28, 2014 at 20:35

2 Answers 2

2

This is because String.prototype.contains() is not supported in Chrome: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains

Just do this:

$.each(superGroup, function(idx, obj) {
    if (idx.indexOf('Addr_Line') !== -1) {
        if (obj != null) {
            currentAddress.push(obj);
        }
    }
});

You might also want to check if idx is a string:

$.each(superGroup, function(idx, obj) {
    if (typeof idx == 'string' && idx.indexOf('Addr_Line') !== -1) {
        if (obj != null) {
            currentAddress.push(obj);
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

According to the docs for String.contains, you can polyfill this Firefox-only method by adding the following code:

if (!('contains' in String.prototype)) {
  String.prototype.contains = function(str, startIndex) {
    return -1 !== String.prototype.indexOf.call(this, str, startIndex);
  };
}

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.