Thursday 15 April 2010

javascript - Getting extra brackets using array push -



javascript - Getting extra brackets using array push -

i trying build little custom logger , noticing array force getting brackets , cannot figure out going on. here sample output

{ "guestcheckout": [ { "log": "product id: 78-1212121", "screenshot": "" }, [ { "log": "product color: undefined product size: 6 lb qty: 2", "screenshot": "" } ], [ { "log": "", "screenshot": "results/screenshots/guest checkout - failed.jpg" } ] ] }

here class has logger function

var logs = {}, curlogs = []; module.exports = { logger: function(log, screenshot) { isscreenshot = screenshot || "false"; curtestname = testname.replace(/ /g,''); curlogs = []; if (isscreenshot == "true") { curlogs.push({ "log": "", "screenshot": log }); } else { curlogs.push({ "log": log, "screenshot": "" }); } if (curtestname in logs) { logs[curtestname].push(curlogs); } else { logs[curtestname] = curlogs; } console.log(curlogs); } }

you notice first log , screenshot wrapped around {} sec instances in wrapped []. logger function called multiple times. think has way force building wrong. thanks

update: 1 solution output looks now

{ "guestcheckout": [ [ { "log": "product id: 36-5173230", "screenshot": "" } ], [ { "log": "product color: undefined product size: 6 lb qty: 2", "screenshot": "" } ], [ { "log": "", "screenshot": "results/screenshots/guest checkout - failed.jpg" } ] ] }

the problem {logs, screenshots} wrapped in brackets.

the issue starts when log test exists. if log exists, pushing array rather object. prepare this, have 2 options. either pull existing array test , force directly, or, force each new log entry test afterwards.

var logs = {}, curlogs = []; module.exports = { logger: function(log, screenshot) { isscreenshot = screenshot || "false"; curtestname = testname.replace(/ /g,''); if (!logs[curtestname]) { // initialize logs entry logs[curtestname] = []; } // logs entry curlogs = logs[curtestname]; if (isscreenshot == "true") { curlogs.push({ "log": "", "screenshot": log }); } else { curlogs.push({ "log": log, "screenshot": "" }); } console.log(curlogs); } }

or

var logs = {}, curlogs = []; module.exports = { logger: function(log, screenshot) { isscreenshot = screenshot || "false"; curtestname = testname.replace(/ /g,''); curlogs = []; if (isscreenshot == "true") { curlogs.push({ "log": "", "screenshot": log }); } else { curlogs.push({ "log": log, "screenshot": "" }); } if (curtestname in logs) { array.push.apply(logs[curtestname], curlogs); } else { logs[curtestname] = curlogs; } console.log(curlogs); } }

javascript node.js

No comments:

Post a Comment