1
I need to remove the elements that have the same value in the property screen_id
keeping whatever has the property id
other than null
.
My sample object:
let userPermissions = [
{
id: 1,
description: Cadastro de usuários,
screen_id: 1,
allow_read: true,
allow_create: true,
allow_update: false,
allow_delete: true
},
{
id: null,
description: "Cadastro de usuários",
screen_id: 1,
allow_read: false,
allow_create: false,
allow_update: false,
allow_delete: false
},
{
id: null,
description: "Tela teste 3",
screen_id: 5,
allow_read: false,
allow_create: false,
allow_update: false,
allow_delete: false
},
]
I need the following result:
[
{
"id": 1,
"description": "Cadastro de usuários",
"screen_id": 1,
"allow_read": true,
"allow_create": true,
"allow_update": false,
"allow_delete": true
},
{
"id": null,
"description": "Tela teste 3",
"screen_id": 5,
"allow_read": false,
"allow_create": false,
"allow_update": false,
"allow_delete": false
},
]
What I tried to:
userPermissions = userPermissions.reduce((arr, item) => {
const removed = arr.filter(i => i['screen_id'] === item['screen_id'] && item['id'] !== null)
return [...removed, item]
}, [])
But not returning the result as expected.
That way I always have to make sure that my element that has id !== null appears before the null id element, right?
– veroneseComS
I tried to do with
reduce
, but in fact it was getting so "disgusting" that I gave up :-)– hkotsubo
Yes, @veroneseComS, elements that have a null ID will be prioritized. Code part responsible so it is:
|| (listed[screenId] === null && id !== null)
, in the evaluation expression of the secondif
.– Luiz Felipe
I did some tests with your code, if my element repeated with id null appears first that the element repeated with id !== null, it is inserted. Here is a reproduction: https://playcode.io/523408
– veroneseComS
Really, @veroneseComS, my mistake. Sorry. :v I edited the answer.
– Luiz Felipe
@Luizfelipe thank you!
– veroneseComS