0

I have following piece of code and this has started breaking after i included Prototype.js into the page.

          function JsonArrayByProperty(objArray, prop, direction) {
            if (arguments.length < 2) throw new Error("sortJsonArrayByProp requires 2 arguments");
            var direct = arguments.length > 2 ? arguments[2] : 1; //Default to ascending

            if (objArray && objArray.constructor === Array) {
                var propPath = (prop.constructor === Array) ? prop : prop.split(".");
                objArray.sort(function (a, b) {
                    for (var p in propPath) {
                        if (a[propPath[p]] && b[propPath[p]]) {
                            a = a[propPath[p]];
                            b = b[propPath[p]];
                        }
                    }
                    a = a.match(/^\d+$/) ? +a : a;
                    b = b.match(/^\d+$/) ? +b : b;
                    return ((a < b) ? -1 * direct : ((a > b) ? 1 * direct : 0));
                });
            }
        }

It breaks at following lines with error

   Uncaught TypeError: Object #<Object> has no method 'match' 

   a = a.match(/^\d+$/) ? +a : a;
   b = b.match(/^\d+$/) ? +b : b;
1
  • Well, apparently a and b are objects, not strings... Commented Jan 16, 2014 at 13:44

1 Answer 1

3

Your problem most likely starts on this line:

for (var p in propPath) {

Once you add prototype.js to your page, you cannot use the common (but incorrect) shortcut of iterating over an array using for(foo in bar). That's because array elements are no longer simple strings or floats, they are full-fledged "extended" objects that happen to evaluate back to strings or floats if you iterate over them correctly.

for(var i = 0; i < propPath.length; i++) {

will get you back on track.

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

2 Comments

thanks mate...it turns out the calling function for this was the culprit where the age old issue of JSON.stringfy(xxxx) not working with prototype surfaced and i will have to make changes to existing code for reason you mentioned. The code was screwing up array in this line of calling function 'var finalData = jQuery.parseJSON(JSON.stringify(someData));'
There's a great page about this here: api.prototypejs.org/language/Array -- read the section about NOT using for/in to loop over an array. If you refactor your code to use yourArray.each() instead, you'll have a much happier time.

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.