简体   繁体   English

如何通过Javascript中的对象键过滤对象数组

[英]How to filter an array of objects by the object's key in Javascript

I am struggling a lot with this.我为此苦苦挣扎。 I have an array of objects and i want to filter it by key, which means if the array has two object with a certain key i only need to keep the last object.我有一个对象数组,我想按键过滤它,这意味着如果数组有两个带有某个键的对象,我只需要保留最后一个对象。

const mockdata = [
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    status: null,
    visibility: 'thid',
  },
];

To look like:看起来像:

const mockdata = [
  {
    id: null,
    visibility: 'true',
  },
  {
    status: null,
    visibility: 'false',
  },
];
let mockdata = [
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    status: null,
    visibility: 'thid',
  },
];

mockdata = mockdata.filter((data, index, self) =>
  index === self.findIndex((t) => (
    t.id === data.id && t.visibility === data.visibility && t.status === data.status
  ))
)

While filtering , I am checking for the index using Array.findIndex which returns the index of first item that matches with the condition , so non unique values are not counted在过滤时,我正在使用 Array.findIndex 检查索引,它返回与条件匹配的第一个项目的索引,因此不计算非唯一值

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

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