A
A
arentyev2015-06-25 12:07:25
JavaScript
arentyev, 2015-06-25 12:07:25

How to make native JavaScript code compatible with libraries/frameworks?

The bottom line is this: the application has a lot of JS code that works with arrays, code like this:

for(var key in collection){
  newCollection.push(JSON.stringify(collection[key]));
}

As a rule, only what we need is in the array, for example, strings. But when Mootools is added to the page, it expands any array with a bunch of additional functions (like clean, getLast, etc.), and such a cycle starts going through not only the array elements, but also these functions. As a result, the application crashes.
So far, a regular data type check has been added with this method:
for(var key in collection){
  if(typeof collection[key] !== 'object') {continue;} // добавлена проверка
  newCollection.push(JSON.stringify(collection[key]));
}

Is this a good solution, or is there something more elegant?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2015-06-25
@aterentyev

all these "unnecessary" properties are added through the prototype, so you need to check:

for(var i in object) {
    if (!object.hasOwnProperty(i)) continue;

    // do stuff
}

in general, for your tasks it is better to use the good old .map
var newCollection = collection.map(function (item) {
    return JSON.stringify(item);
});

D
Denis Ineshin, 2015-06-25
@IonDen

Use bare objects to store data.
To create such an object and strip it of all the inherited tinsel from the prototype, do this:

var collection = Object.create(null);
// теперь цикл по этой коллекции
for (var key in collection) {
    // будет выдавать вам то что нужно без всяких проверок
}

A
arentyev, 2015-08-03
@aterentyev

As it turned out, a regular for loop (not for in) can also be used, because it only goes through the values ​​of the array, not taking into account what lies in the prototype

for(i=0; i < a.length; i++){
console.log(a[i]); 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question