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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.