0

Say I've got a piece of JSON that I'm storing in a file:

//data.json
{
  "table": [
    {
      "text": "Balance",
      "value": "0.00" 
    }
  ]
}

Then while I'm iterating over a collection, I want to set a var to the value of the json stored in the file, add some data to it, and then do something else with it. My Java-addled brain tried this:

financials.forEach(function (value) {
  ...
  jsondata = require('data.json')
  jsondata.table.push(newTransaction)
  ...
  doSomethingElse(jsondata)
}

What is the best and most idiomatic way to do this in javascript/node? If I try use 'require', I think the caching only sets the value of jsondata once right at first iteration of the loop, and the var jsondata keeps growing instead of resetting, causing data to leak between loops.

(I'm probably also wrong to try this in a foreach.)

sim
  • 3,552
  • 5
  • 23
  • 23
  • 1
    You could parse the JSON and use as an object. At the end you could parse it back. https://stackoverflow.com/questions/5726729/how-to-parse-json-using-node-js – municool Jan 18 '18 at 09:47

1 Answers1

0

I’m not sure I understand what the exact problem is — but if assuming when you mean leaking you mean previous work from the loop is showing up.

Anyway, you’re right require caches. But your other problem is you’re always working off a reference.

I’d move the require out of the forEach loop for clarity — and inside the forEach I’d create a copy of the data with Object.assign. That way you’re not editing the source, which would persist since Objects are passed/copied by reference.

prasanthv
  • 2,442
  • 2
  • 21
  • 17