I've been attempting to add an object to an array of objects only if that specific object is not already in the array. If it is present, the object should be updated instead.
My requirement is to achieve this using es5.
Below is my current approach:
var database = require('../../database');
var autoincrementId = require('../../helpers/autoincrement-id');
var books = database.Books;
function Book(title, author, summary) {
this.title = title;
this.author = author;
this.summary = summary;
}
Book.prototype.createBook = function () {
var id = autoincrementId(id, database.Books); //autoincrement database id
var copies = 1;
var title = this.title.toLowerCase(), author =
this.author.toLowerCase(), summary = this.summary.toLowerCase();
if (!books.length) {
books.push({id: id, title: title, author: author, summary: summary, copies: copies});
} else {
for(var book in books) {
if(books[book].title === title) {
books[book].copies += 1;
break;
}
books.push({id: id, title: title, author: author, summary: summary, copies: copies});
}
}
};
However, when I execute the following:
var abook = new Book('J', 'k', 'l');
var bbook = new Book('M', 'N', 'o');
abook.createBook();
abook.createBook();
bbook.createBook();
bbook.createBook();
console.log(books);
I am getting the following result:
[ { id: 1, title: 'j', author: 'k', summary: 'l', copies: 2 },
{ id: 2, title: 'm', author: 'n', summary: 'o', copies: 2 },
{ id: 3, title: 'm', author: 'n', summary: 'o', copies: 1 } ]
Instead of:
[ { id: 1, title: 'j', author: 'k', summary: 'l', copies: 2 },
{ id: 2, title: 'm', author: 'n', summary: 'o', copies: 2 }]
I need help understanding what is causing this issue with the code. Why is it updating and inserting on the second attempt, and how can I resolve this?