Ibrahim Abouhashish Ibrahim Abouhashish -4 years ago 249
Node.js Question

Node.js and Express, data.push is not a function

I'm getting an error pushing newTask to allTasks, with the error being

TypeError: allTasks.push is not a function


data
is the JSON data pulled from a file using
fs


var allTasks = JSON.parse(data);
var newTask = {
id: Date.now(),
title: "BAM",
description: "BOOM",
image: "SLAM"
};
allTasks.push(newTask);


I've tried declaring
allTasks
as an array before parsing JSON But that didn't work either.

data.json is:

{
"tasks": [{
"id": 1,
"title": "something",
"description": "do some shit",
"image": "image URL1"
}, {
"id": 2,
"title": "something2",
"description": "do some shit2",
"image": "image URL2"
}]
}

Answer Source

Your data after being parsed from a JSON string is an object, hence why .push isn't working.

It looks like what you want to do is allTasks.tasks.push(newTask);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download