Ilia Soloveychik
Ilia Soloveychik

Reputation: 101

How to push object to specific array correctly in express.js?

In the function below my aim is write a JSON file with array of data (in string). But push() function that is under comments stop executing code. Without this line of code everything works. However, I need to use this function. What should I do or maybe I should use something different at all?

router.put('/insert_Data', function (req, res, next) {
  let body = req.body;
  let data = [];
  data.push(body['d']);
  let jsonData = [];

  for (let i = 0; i < data.length; i++) {
    let from = Number(data[i].from);
    let to = Number(data[i].to);
    let type = Number(data[i].type);
    let time = Number(data[i].time);
    let price = Number(data[i].price);
    let line = data[i].line;
    let coin = data[i].coin;
    from = from ? from : 0; 
    to = to ? to : 0;
    type = type ? type : 0;
    time = time ? time : 0;
    price = price ? price : 0;
    let item = `${from},${to},${type},${time},${price},${line},${coin}`;
    console.log('item', item);
    console.log('jsonData', jsonData);
    //jsonData[i].push(item); // TODO: здесь не выполняется!
    console.log('jsonData', jsonData);
  }
  console.log('after', jsonData);
  jsonData = JSON.stringify(jsonData, null, 1);
  // create new JSON
  fs.writeFileSync('output.json', jsonData, function(err){
    console.log(err.message);
  });

  
  
  
  res.end();
});

I use Postman to check this code. req.body is the following JSON:

{
    "d": {
        "from": 4444,
        "to": 222,
        "type": 322,
        "time": 222222,
        "price": "334",
        "line": "333",
        "coin": 333
    }
}

router variable is simple, it is only express.js running on port 5000.

Upvotes: 0

Views: 1498

Answers (1)

Gabriel Lima
Gabriel Lima

Reputation: 499

You can only push on arrays. What you are doing is trying to push in an element of an array, but the array is empty. I guess what you're trying to do is jsonData[i] = item or jsonData.push(item) (probably the first, though).

Upvotes: 2

Related Questions