Can anyone help me with a problem I'm facing? Every time I push objects into an array of objects, it duplicates the existing objects in that array. The duplicates are only removed after a page reload. I suspect it has something to do with reference. I've tried copying the object being pushed and creating a new object with properties, but it hasn't worked. Any assistance would be greatly appreciated. Thank you.
// The persons array is an array of objects
import { persons } from './main.js';
let entriesFound = []
let data = localStorage.getItem('entriesFound') ;
if(data){
entriesFound = JSON.parse(data)
loadList(entriesFound)
}
//Renders the search results to the UI from localStorage
function loadList(array) {
for(let el of array) {
const html =
`<div id="${el.id}" class="item2">
<div class="info2">Name:<div class="name">${el.name}</div></div>
<div class="info2">Date of birth:<div class="born">${el.dob}</div></div>
<div class="info2">Age:<div class="age">${el.age}</div></div>
<div class="info2">Place of birth:<div class="city">${el.city}</div></div>
<div class="info2">ID:<div class="id">${el.id}</div></div>
<div class="info2">Entered:<div class="added">${el.entered}</div></div>
</div>`;
document.querySelector('.searchResult').insertAdjacentHTML('beforeend', html)
}
}
//Search button to search for entry (in the persons array) that matches the condtional
export const searchBtn = document.querySelector('.search').addEventListener('click' , function() {
// Get search string from search bar
const name = document.querySelector('.searchInput')
// persons array
persons.filter( el => {
if(el.name === name.value) {
entriesFound.push(el); // Pushes the object (el) to the entriesFound array
} // I guess this is were it goes wrong
})
addItem(entriesFound)
name.value = ""
localStorage.setItem('entriesFound', JSON.stringify(entriesFound))
})
// Renders the new search result to the UI
function addItem(entries) {
for( let item of entries) {
const html =
`<div id="${item.id}" class="item2">
<div class="info2">Name:<div class="name">${item.name}</div></div>
<div class="info2">Date of birth:<div class="born">${item.dob}</div></div>
<div class="info2">Age:<div class="age">${item.age}</div></div>
<div class="info2">Place of birth:<div class="city">${item.city}</div></div>
<div class="info2">ID:<div class="id">${item.id}</div></div>
<div class="info2">Entered:<div class="added">${item.entered}</div></div>
</div>`;
document.querySelector('.searchResult').insertAdjacentHTML('beforeend', html)
}
}