Adding items to an array of objects creates additional copies of the objects already present in the array

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)
        }
}

Answer №1

Identified the issue. The addItem function is iterating through the entire entriesFound array, when it really only needs to add a single entry to the search results.

     persons.forEach( el => {
        if(el.name === name.value) {
           addItem(el)                 <---- here, el represents an object from 
                                             the persons array of objects!
           entriesFound.push(el);   
        }                           
    })
        addItem(entriesFound)
        name.value = ""
        localStorage.setItem('entriesFound', JSON.stringify(entriesFound))
})

// Displays the updated search result on the interface
function addItem(entry) {
                                       <--- removed the loop altogether!
        const html = 
                `<div id="${entry.id}" class="item2">
                <div class="info2">Name:<div class="name">${entry.name}</div></div>
                <div class="info2">Date of birth:<div class="born">${entry.dob}</div></div>
                <div class="info2">Age:<div class="age">${entry.age}</div></div>
                <div class="info2">Place of birth:<div class="city">${entry.city}</div></div>
                <div class="info2">ID:<div class="id">${entry.id}</div></div>
                <div class="info2">Entered:<div class="added">${entry.entered}</div></div>
                </div>`;
    
             document.querySelector('.searchResult').insertAdjacentHTML('beforeend', html)
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the benefits of looping with node.js require()

Currently, I have defined the required files as shown below. constantPath = './config/file/' fileAA = require(path.resolve(constantPath + 'A-A')), fileBB = require(path.resolve(constantPath + 'B-B')), fileCC = require(path.r ...

Encountering the error "Uncaught reference error: $ is not defined" despite ensuring that scripts are loading in the correct order. However, the scripts work from the

Encountering an Issue: "Uncaught ReferenceError: $ is not defined" Whenever I try to utilize $('#someid') in my custom JavaScript code within an Electron app. All scripts are properly arranged in my HTML file: <script type="text/javascri ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

Sharing data between functions within an AngularJS service

I have been struggling to find a solution for this issue. I have a service where I am logging a URL and then passing it into my getData() function. However, when I try to use it, it returns undefined. I have attempted different methods including moving t ...

Encountering a problem while parsing JSON in Ruby: Uncaught exception 399 - unexpected token detected!

Whenever I try to use JSON.parse(response['data']), Ruby throws an error: Uncaught exception: 399: unexpected token at ... I can't figure out why this is happening. In casperjs, I send the following data back to Ruby: this.echo('{"da ...

Update a JavaScript variable with fresh information and then execute JSON parsing

I have implemented this code to display a Verite Timeline on my webpage: <div id="timeline-embed"></div> <script type="text/javascript"> var timeline_config = { width: "100%", height: "100%", debu ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...

Proper method for retrieving and displaying information from a targeted JSON through an API

Utilizing a third-party API requires specifying the desired fields in the request. For instance: axios.get("APIURL", { params: { fields: ["username", "phone", ...etc] } }) The response is typically structured like this: { "data": [{ ...

Changing the URL locale using Next.js router.push is unsuccessful

I am attempting to switch the locale by connecting the onClick event to two separate <div> elements: import { useRouter } from 'next/router' // other codes const router = useRouter() const changeLocale = (locale) => { router.push({ ...

When passing a numeric value like 1 or 2 to the function in ajax, it functions correctly. However, when attempting to parse a variable, it does

I am facing an issue with my AJAX function. It works perfectly fine when I pass a number as a parameter, but not when I pass a variable. function display_message(userID) { $.ajax({ url: "displaychat.php", method: "post", data: { toui ...

Adding node-neat along with other files to the node-sass grunt task

I've been facing some challenges with using node-neat in conjunction with grunt-sass, specifically when trying to add additional include paths. Initially, everything works fine when I set it up like this: options: { includePaths: require(' ...

Ways to identify when a modal window is being closed in the angular-ui $modal component

I am currently utilizing the $modal from angular-ui to generate a modal window. Below is the code snippet for creating the modal: this.show = function (customModalDefaults, customModalOptions, extraScopeVar) { //Create temporary objects to work with s ...

Difficulty in implementing Handlebars handler for dropdown onchange event

Currently, I am implementing Express alongside Handlebars for the front-end of my project. My aim is to trigger an event and read the value of the selected option in the dropdown within 'home.handlebars' when it changes, through 'index.js&ap ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

Error: You forgot to include a name after the dot operator

I am facing an issue where I am unable to use YUIcompressor to compress a file. The script is running smoothly, but I am encountering the error missing name after . operator on line 3 of this script: Specifically at: "+ source.response.chars[k].name +" I ...

Is it truly challenging to create a set of 10 unique random numbers?

Generating 10 unique random numbers (0-99) should be an easy exercise. 1.- Please help me generate 10 random numbers and store them in an array without any repeats. Despite my efforts, all the answers I find online are too complicated or lengthy. In the ...

How to Extract an Object from an Array using React

I have a situation where I am fetching data from an API using axios. Specifically, on my invoice details page, I am trying to retrieve data for only one invoice using the following code: const id = props.match.params.id; const invoice = useSelecto ...

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

The directive binding value is accurate, however it is failing to return a true result

The behavior of a custom directive is puzzling me. When I directly pass in a value, it works fine. However, if I bind the value to a variable, it doesn't work as expected. Interestingly, when I use console.log to show the value, it appears to be corre ...

Ways to automatically change a URL into a clickable link upon pasting

When attempting to paste a URL into the text box such as https://stackoverflow.com/, it does not automatically convert to a hyperlink. I previously tried using regular expressions in this related question. The function I implemented worked correctly, howe ...