1

I'm struggling to push a new object into an array. At the moment the code below seems to be simply overwriting a single object. I can see the data I want to push to the array going through the console but it's just not storing a new object. Any ideas?

fs.readFile('check.json', function (err, check) {
    if (err) throw err;
    var newData = JSON.parse(check);

    var tempData =[];
    for (var index=0; index<newData.length; index++){
        tempData.push(newData);
        }
    tempData = newData;
});
2
  • You are assigning the last element to the array at the end? tempData = newData; Commented Oct 15, 2015 at 21:26
  • you're overwriting the tempData array by assigning it with newData in the last line Commented Oct 15, 2015 at 21:27

1 Answer 1

3

The typical approach for iterating arrays and then pushing objects to them would be this

var tempData =[];
for (var index=0; index<newData.length; index++){
    tempData.push(newData[index]);
    //                     ^add index
}
//tempData = newData; remove assignment which overwrites array
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Can you offer any insight into how that pushes externally with fs? The external json comes back as undefined. Travis J

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.