Reputation: 429
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!
Upvotes: 1
Views: 244
Reputation: 148
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);
}
Upvotes: 2