1

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, e.g 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!

4
  • 1
    Array#find might be useful here. Given the right callback, it'll find the object with the matching targetId, which you can then update directly (eg. match.color = color;) since the object will be by-reference. If match isn't found, you can handle that situation by adding it to the array. Commented Apr 28, 2020 at 12:37
  • 1
    first things first thisJSON is not JSON, it's a Javascript object Commented Apr 28, 2020 at 12:38
  • @Liam absolutely true! Commented Apr 28, 2020 at 12:50
  • @NiettheDarkAbsol will try, thanks! Commented Apr 28, 2020 at 12:50

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

this is *almost* what i'm after. It skips the element when it already exists, but I want it to update with a new value instead
Updated the answer
works like a charm, thanks! another approach would have been to use findIndex as described here stackoverflow.com/a/41938641/10727821

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.