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!
Array#findmight be useful here. Given the right callback, it'll find the object with the matchingtargetId, which you can then update directly (eg.match.color = color;) since the object will be by-reference. Ifmatchisn't found, you can handle that situation by adding it to the array.thisJSONis not JSON, it's a Javascript object