如何清理节点中的对象数组?手动遍历它返回“对象对象”

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

本文关键字:对象 遍历 返回 对象对象 节点 何清理 数组      更新时间:2023-09-26

我有一个这样的对象数组:

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

我正在尝试通过在服务器端手动迭代对象来清理值,但该模块只会在控制台中返回[ '[object Object]', '[object Object]' ]

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);
 }
});

谁能告诉我如何正确消毒物体?

这样的事情应该可以解决问题:

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.
    }; 
};