Generate a unique JavaScript object without any redundancy

I am in the process of creating a JavaScript object that needs to be processed through a PHP API.

The structure should resemble the following:

[{
  'targetId': 'roof',
  'color': 'red'
},
{
  'targetId': 'window',
  'color': 'green'
}]

The values should be dynamically generated based on user input, such as clicking on elements like "roof" or "window", with various color options for each.

Currently, my implementation looks like this:

let requestJSON = []
let timeout = undefined

myElement.addEventListener('click', function(e) {
    let target = e.target;
    let targetID = target.id
    let color = colors[getNumber(e.target)]
    target.setAttribute('fill', color)
    let thisJSON = 
    {
        'targetId': targetID,
        'color': color
    }
    updateRequest(thisJSON)
})

function updateRequest(input) {
    if (timeout != undefined) clearTimeout(timeout)
    requestJSON.push(input)
    timeout = setTimeout(() => {
        console.log(requestJSON)
        // makeRequest(requestJSON)
    }, 1000);
}

function makeRequest(body) {
    body = JSON.stringify(body)
    fetch('https://myapi.com/setcolor', {
        body: body,
        method: 'POST'
    })
    .then((res) => {
        return console.log(res.json())
    })
    .catch((error) => {
        console.error(error)
    })
}

However, the current implementation allows for duplicate entries in the JavaScript object even if the element already exists.

To address this issue, I need to ensure there are no repeated values inside the JavaScript object by checking if the targetId already exists and updating the corresponding value instead of adding a new entry.

What would be the best approach to achieve this? Thank you for any help!

Answer №1

To determine if the Object with the specified targetId already exists, you can utilize the Array.find() method. Follow these steps to modify the updateRequest(input) function:

function updateRequest(input) {
    if (timeout !== undefined) clearTimeout(timeout);
    let foundObj = requestJSON.find(elem => elem.targetId === input.targetId);
    
    // Update color if targetId already exists in requestJSON, otherwise push the object
    if (foundObj) {
        foundObj.color = input.color;
    } else {
        requestJSON.push(input);
    }
    
    timeout = setTimeout(() => {
        console.log(requestJSON);
        // makeRequest(requestJSON)
    }, 1000);
}

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

gulp - synchronized gulp.pipe(gulp.dest) execution

Here's my challenge: I have two tasks, where Task B depends on Task A. In Task A, one of the requirements is to loop through an array and then use gulp.dest, but it seems like Task B will be executed before Task A is completed. The main goal of Task ...

Tips for moving directly to a section while maintaining a set distance from the top of the page

I'm currently implementing code for a smooth scroll to a section when clicking on a navigation menu item: // handling links with @href starting with '#' $(document).on('click', 'a[href^="#"]', function(e) { ...

The button designed to delete the parent container div is ineffective when applied to dynamically generated divs

I'm in the process of developing a JavaScript to-do list app from scratch. Everything is functioning properly except for the button that is supposed to remove items from the list. Here is the HTML snippet: <div class="todolistcontainer"& ...

Listening for a custom event with jQuery

Here is the code snippet that I am working with: myCustomMethod(function(){ $(document).on('click','#element',function(){ console.log('First call'); }); }); setTimeout(function(){ myCustomMethod(function( ...

Identifying with a jQuery IF statement all input fields that contain null values in order to eliminate the respective elements

My goal is to create a jQuery script that checks all input fields to see if they are empty. If an input field is empty, I want to remove the child image of the next occurring span element. Here is what I have attempted so far: if ($("input").val() == "") ...

JSON objects not loading properly in Bootstrap table

I am facing an issue where my ajax script successfully sends JSON objects to the browser, but the table fails to load the JSON object. Here is my Ajax script: $.ajax({ type : "POST", url : "getLabels.jsp", data : "mail ...

Shifting a division using insertAfter

Hey there! I'm having a bit of trouble using the insertAfter function. In each product in my store, I need to position an "add to cart" button after the price. This is the code I tried: <Script type="text/javascript" > jQuery(document).read ...

Presenting a Random Term from an Array in Dual Locations

<input type="button" id="btnSearch" value="Search" onclick="myFunction();" /> <div id="message"> <p></p> </div> <br> <div id="message"> <p></p> </div> <script type="text/javascript"&g ...

What sets apart genuine user interactions from programmatically generated actions?

Working with webkit notifications on Chrome has presented a challenge. The window.webkitNotifications.requestPermission method must be called from a user action, such as a click. Attempting to call it at any other time will not have any effect and will not ...

Having issues with the jQuery toggle functionality

var resultsList = $("#test"); resultsList.text("Hello. This is jQuery!"); var tB = jQuery("#toggleButton"); tB.on("click", function() { resultsList.toggle(400); }); The syntax appears to be correct as there are no errors reported in the browser cons ...

executing the following event in Node.js

Is it feasible to execute only a portion of the code on each iteration of the event loop in an application where requests can take a second or two? Consider the following scenario: function foo() { ...critical code... ...start processing the next ...

Invisible tag remains unseen

I need to dynamically hide some text and show specific labels upon clicking a button. How can I achieve this? <body> <div id="middle"> <div id="left"> </div > <div id="m"> ...

Switch the background color alternately from red to green every second

Need help with a webpage that changes the background color every second using JavaScript. The issue lies in figuring out how to correctly change the variable within the function. Here's an example of the code: <!DOCTYPE html> <html> ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Having trouble with connect-busboy not calling the callback when using NodeJS, AngularJS, and File Upload?

Click here for the sources I am currently working on implementing a NodeJS server that allows file uploads using connect-busboy from AngularJS with the help of angular-file-upload for later analysis. The issue I'm encountering is that the callback f ...

Ways to execute multiple queries in ReactJS using AWS Amplify

I'm having trouble querying multiple Dynamo databases in React.js. I initially attempted to define each component in separate classes and import them, but that didn't work. Then I tried defining both components in the same class, which resulted i ...

Retrieving data from a promise in Redux

Is there a way to access the data of the first dataElement in the array and log its name using console.log? import React, { Component } from 'react'; class Submit extends Component { componentDidMount() { const programStage = this.p ...

Employing ng-style for establishing background when the value does not align

Greetings all! I am using ng-repeat to create a list of items within a ul element. Within the json data, there is a specific value that I want to highlight if it does not match a predefined string. Here's what I have so far: ng-style="{'backgro ...

What is the most efficient way to organize JSON data in a tree structure using JavaScript?

I have a JSON data structure that I need to transform into a different format. The original JSON format: values = an array containing objects that need to be filtered by action === 'commented' comment = an object with the comment, n Tasks, and ...

Can you explain the distinction between a synchronous and asynchronous request in terms of their async parameter values (true/false)?

Can you explain the difference between setting async=false and async=true when utilizing the open method of the XMLHttpRequest? function GetXML() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new X ...