【问题标题】:how to retrieve the last unique object in an array如何检索数组中的最后一个唯一对象
【发布时间】:2022-01-23 12:56:27
【问题描述】:

大家好,有没有一种方法可以检索数组中的最后一个唯一对象 在下面的代码中,第一个和第二个索引处的 id 是相同的,有没有办法可以用相应的对象检索 id 的最后一次出现

0: {id: 'tra.528555295', name: 'heart'}
1: {id: 'tra.528555295', name: 'heart-outline'}
2: {id: 'tra.528555301', name: 'heart'}
3: {id: 'tra.528555301', name: 'heart-outline'}

【问题讨论】:

  • 预期输出是什么?
  • @goto 我只需要在数组中最后出现相似 id 的对象,就像我在索引 1 处给对象的代码中一样,应该返回索引 3

标签: javascript arrays object indexing


【解决方案1】:

您需要遍历整个数组并使用找到的唯一 ID 跟踪“最后一个”对象。

这是一种方法,您可以使用 Array.prototype.reduce 遍历数组并跟踪找到的“最后一个”ID,然后使用 Object.values 提取具有唯一 IDs 的值:

const arr = [
  { id: "tra.528555295", name: "heart" },
  { id: "tra.528555295", name: "heart-outline" },
  { id: "tra.528555301", name: "heart" },
  { id: "tra.528555301", name: "heart-outline" }
];

const result = Object.values(
  arr.reduce((accumulator, item) => {
    const { id, ...rest } = item;
    return {
      ...accumulator,
      [id]: { id, ...rest }
    };
  }, {})
);

console.log(result);

【讨论】:

    【解决方案2】:

    如果你能提供我建议的 id:

    const findLastElementOfId = (arr, id) => {
        return arr.filter(object => object.id === id).at(-1)
    }
    

    过滤数组中具有您要查找的 id 的对象并返回最后一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 2013-05-28
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      相关资源
      最近更新 更多