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!