如何过滤数组仅选择React中对象同一ID的最后一个更改的值

发布于 2025-01-28 15:12:11 字数 467 浏览 2 评论 0原文

这是我在Avfield的Onchange上运行的功能

let selectedFieldArray = []

const templateValue = (e) => {
    const fieldObject = {
      "id": e.target.name,
      "value": e.target.value,
    }
    selectedFieldArray.push(fieldObject)
    const uniqueID = selectedFieldArray.filter((obj, id, array) => {
      return id === array.findIndex((t) => (
        t.id === obj.id
      )) 
    })
  }

,但是在solutionId中它仅选择数组的第一个对象,而不是数组中的最后更新对象。

This is the function i run on OnChange in AvField

let selectedFieldArray = []

const templateValue = (e) => {
    const fieldObject = {
      "id": e.target.name,
      "value": e.target.value,
    }
    selectedFieldArray.push(fieldObject)
    const uniqueID = selectedFieldArray.filter((obj, id, array) => {
      return id === array.findIndex((t) => (
        t.id === obj.id
      )) 
    })
  }

but in uniqueID it only picks first object of array not the last updated object in array.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百思不得你姐 2025-02-04 15:12:11

而不是使用arr.findindex您可以使用arr.findlastindex

let selectedFieldArray = [];
const templateValue = (e) => {
  const fieldObject = {
    "id": e.target.name,
    "value": e.target.value,
  }
  selectedFieldArray.push(fieldObject) const uniqueID = selectedFieldArray.filter((obj, id, array) => {
    return id === array.findLastIndex((t) => (t.id === obj.id))
  })
}

Instead of using arr.findIndex you can use arr.findLastIndex

let selectedFieldArray = [];
const templateValue = (e) => {
  const fieldObject = {
    "id": e.target.name,
    "value": e.target.value,
  }
  selectedFieldArray.push(fieldObject) const uniqueID = selectedFieldArray.filter((obj, id, array) => {
    return id === array.findLastIndex((t) => (t.id === obj.id))
  })
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文