computerguy1234 computerguy1234 - 3 years ago 473
Node.js Question

nodeJS: forEach loop is not a function, error

I'm using

function and I get an error that

parsedBody.forEach is not a function.

produces a value and I've used
in other methods and the function works fine. So why is
not working in this case?

Edit: parseBody is an object. How do I turn it into an array?


console.log('- before');{
url: `${dc_link}/audit`, //includes dc_IP, dc_port and /audit
"jwt": jwt.sign(token, jwtSecret)
}, function(error,response,body){ //*
console.log('path 0');
console.log('error:', error);
let parseBody = JSON.parse(body);
console.log('parseBody.additionalData', parseBody.additionalData);

parseBody.forEach(function(element){ //**HERE
console.log('path 3');



[stdout] - before
[stdout] start respondWithJSON
[stderr] /app/server.js:435
[stderr] parseBody.forEach(function(element, index, array){ //*
[stderr] ^
[stderr] TypeError: parseBody.forEach is not a function
[stderr] at Request._callback (/app/server.js:435:15)
[stderr] at Request.self.callback (/app/node_modules/request/request.js:188:22)
[stderr] at emitTwo (events.js:106:13)
[stderr] at Request.emit (events.js:191:7)
[stderr] at Request.<anonymous> (/app/node_modules/request/request.js:1171:10)
[stderr] at emitOne (events.js:96:13)
[stderr] at Request.emit (events.js:188:7)
[stderr] at IncomingMessage.<anonymous> (/app/node_modules/request/request.js:1091:12)
[stderr] at IncomingMessage.g (events.js:286:16)
[stderr] at emitNone (events.js:91:20)
[stdout] path 0
[stdout] error: null
[stdout] parseBody.additionalData iAAGtYgBAGkCBFoW4F4DARkDAQkDAQUDAQ

Answer Source

parseBody appears to be an object since you're accessing it with dot notation. You need an array to use the forEach method. Turn parseBody into an array, and the problem is solved.

To turn it into an array, here is one possible solution:

  var arr = Object.keys(parseBody).map(function(key){ return parseBody[key]; });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download