简体   繁体   中英

Create a JavaScript object without repeating

I'm trying to create a JavaScript object that should be processed by a PHP API.

It should look like this:

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

the values should be generated on user input, eg each time a the user clicks an element called "roof", it will loop through some colors, same for "window" (+ multiple others).

What I have right now is 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)
    })
}

Currently, this will push the same element to the JavaScript object multiple times, even if it already exists.

What I need to achieve is that there shouldn't be any repeating values inside my JavaScript object: before the element is pushed to the array, the function should check if the targetId already exists and only update the corresponding value.

What would be the right approach here? Thanks in advance!

You can use Array.find() to check if the Object with given targetId already exists. So, make the following changes to updateRequest(input) :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM