2

My Javascript is interacting with the following 2 JSON files:

readers.json:

[
    {
    "readerID": 1,
    "name": "Maria",
    "weeklyReadingGoal": 350,
    "totalMinutesRead": 5600,
    "bookID": 65
    },
    {
    "readerID": 2,
    "name": "Daniel",
    "weeklyReadingGoal": 210,
    "totalMinutesRead": 3000,
    "bookID": 65
    }
]

Books.json

[
    {
    "bookID": 65,
    "title": "Goodnight Moon",
    "author": "Margaret Wise Brown",
    "publicationYear": "1953"
    },
    {
    "bookID": 75,
    "title": "Winnie-the-Pooh",
    "author": "A. A. Milne",
    "publicationYear": "1926"
    }
]

At the moment, I am able to DELETE a book from book.json

When I delete a book, & that book's bookID exists in a reader.json object, I want to update that ID to 0.

For example, if I delete a book where bookID = 65, I want to change all the bookID's that are equal to 65 in reader.json to null.

Below is my code, I can provide additional code if required:

Books.js:

var data = getBookData();

var pos = data.map(function (e) {
  return e.bookID;
}).indexOf(parseInt(req.params.id, 10));

if (pos > -1) {
  data.splice(pos, 1);
} else {
  res.sendStatus(404);
}

saveBookData(data);

var readerData = getReaderData();
var bookID = req.params.id;
console.log('BOOK ID - ' + bookID); // prints: BOOK ID - 47
readerData.forEach(function (x) {
  if (x.bookID === bookID) {
    x.bookID = null;
  }
  else {
    console.log('Deleted book was not associated with any reader');
    console.log('BOOK ID in else - ' + x.bookID); // prints: BOOK ID in else - 47
  }
});

saveReaderData(readerData);
res.sendStatus(204);
});

function getReaderData() {
    var data = fs.readFileSync(readerFile, 'utf8');
    return JSON.parse(data);
}

When I run this code, the book is removed from books.json, but the matching bookID's in readers.json are remaining the same.

Also, in the else block above, the matching bookID's are being logged, but for some reason the code is not flowing into the if block.

3
  • you want to replace each matching bookID to null ? Commented Apr 26, 2019 at 9:11
  • I want to loop through readers.json, & replace all matching bookID's within that JSON to null. Commented Apr 26, 2019 at 9:15
  • @AmitBaranes I've updated my books.js above to show how I'm getting the bookID & deleting it. I then want to loop through readers.json & replace all matching bookID's within that to null Commented Apr 26, 2019 at 9:16

1 Answer 1

1

You can loop on the readers and perform a check of the bookID. Is this what you wanted?

Your mistake is to use indexOf on an array, because it will returns only the first match to you.

const readerData = [{
    "readerID": 1,
    "name": "Maria",
    "weeklyReadingGoal": 350,
    "totalMinutesRead": 5600,
    "bookID": 65,
  },
  {
    "readerID": 1,
    "name": "Maria",
    "weeklyReadingGoal": 350,
    "totalMinutesRead": 5600,
    "bookID": 70,
  },
  {
    "readerID": 2,
    "name": "Daniel",
    "weeklyReadingGoal": 210,
    "totalMinutesRead": 3000,
    "bookID": 65,
  },
];

const bookID = 65;

// Treat every reader
readerData.forEach((x) => {
  // If the bookID is the one we are looking for, set it as null
  if (x.bookID === bookID) {
    x.bookID = null;
  }
});

console.log(readerData);


So. Applied to your code

var readerFile = 'server/data/readers.json';

router.route('/')
  .delete(function(req, res) {
    var readerData = getReaderData();

    var bookID = parseInt(req.params.id, 10);

    // Have we found any occurence of the bookID ?
    var found = false;

    // Treat every reader
    readerData.forEach(function(x) {
      // If the bookID is the one we are looking for, set it as null
      if (x.bookID === bookID) {
        x.bookID = null;

        found = true;
      }
    });

    // If we haven't found any occurence, returns an error
    if (!found) {
      res.sendStatus(404);

      return;
    }

    // Save the changes
    saveReaderData(readerData);

    res.sendStatus(204);
  });

function getReaderData() {
  var data = fs.readFileSync(readerFile, 'utf8');

  return JSON.parse(data);
}
Sign up to request clarification or add additional context in comments.

7 Comments

FYI. In case your userbase uses IE, arrow functions are not supported in IE -> caniuse.com/#feat=arrow-functions
Yeah, thanks you to point it out. I'm so used to it now. Just replace () => { by function() {
Thanks for your answer. Yes, I want to check if the BookID of each reader matches the passed in BookID. If it does, then set the BookID of that Reader to null. Your forEach above, which piece of my code to I replace that with?
I've edited my post. Please takes time to understand. Do not just copy paste it
I've merged your code with mine above, please take a look. Currently, it is deleting the book record from books.json but now it isn't doing anything to reader records in readers.json that have that same BookID
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.