문제

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