繁体   English   中英

创建 JavaScript object 不重复

[英]Create a JavaScript object without repeating

我正在尝试创建一个 JavaScript object 应该由 PHP ZDB974238714831DE634A7ACED1 处理

它应该如下所示:

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

这些值应在用户输入时生成,例如,每次用户单击一个名为“屋顶”的元素时,它将循环通过一些 colors,与“窗口”相同(+ 多个其他元素)。

我现在拥有的是这样的:

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)
    })
}

目前,这会将相同的元素推送到 JavaScript object 多次,即使它已经存在。

我需要实现的是,在我的 JavaScript object 中不应该有任何重复值:在将元素推送到数组之前, targetId应该只检查相应的值是否已经存在。

这里的正确方法是什么? 提前致谢!

您可以使用Array.find()检查具有给定targetId的 Object 是否已经存在。 因此,对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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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