javascripthtmlnode.jsxss

how to sanitize an array of object in node? Iterating through it manually returns 'object Object'


I have an array of objects like this:

var msg =  [ 
             { msg: 'text' },
             { src: 'pic.jpg',id: 21,title: 'ABC' } 
           ];

I'm trying to sanitize the values by iterating manually through the object at the server side, but the module would just return [ '[object Object]', '[object Object]' ] in the console.

socket.on('message', function(msg){
 if (io.sockets.adapter.rooms[socket.id][socket.id] == true)
 {
   var fun = [];
   for(var j in msg){
     fun[j] = sanitizer.sanitize(msg[j]);
   };

   console.log(fun);

   io.sockets.in(socket.room).emit('message',fun);
 }
});

Can anyone show me how to properly sanitize the object?


Solution

  • Something like this should do the trick:

    var fun = [];
    for(var i = 0; i < msg.length; i++){  // Don't use for...in to iterate over an array.
        fun[i] = msg[i];                 // Copy the current object.
        for(var j in fun[i]){           // Iterate over the properties in this object.
            fun[i][j] = sanitizer.sanitize(fun[i][j]); // Sanitize the properties.
        }; 
    };