Вопрос

How can I escape all attributes of an object in JS?

var literal = {
    valid:'thisIsAValidValue', 
    toEscape:'ThîsStringNéédsToBéEscàped'
};

//Does not work
escape(literal)

//Does not work either, how to loop over attributes?
$.each(literal.attributes, function(){
   this = escape(this);
});
Это было полезно?

Решение

First, are you really sure you want escape? It's an old, deprecated function.

But in any case, the form of the code doesn't change, regardless what function you call to transform the values:

var key;
for (key in literal) {
    literal[key] = escape(literal[key]);
}

Or using jQuery's $.each, since you seem to be using jQuery:

$.each(literal, function(key, value) {
    literal[key] = escape(value);
});

If you want to be sure not to process inherited properties (although your literal won't have any enumerable inherited properties unless someone has been Very Naughty Indeed and added an enumerable property to Object.prototype):

var key;
for (key in literal) {
    if (literal.hasOwnProperty(key)) {
        literal[key] = escape(literal[key]);
    }
}

More about for-in on my blog: Myths and realities of for..in

Другие советы

Try this

   $.each(literal, function(key,value){
       literal[key] = escape(value);
    });
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top