2021-08-31

How to filter and sort nested objects? ReactJS

Data sample:

   const people = [
         1:{
           id : 1,
           name: 'James',
           age: 31,
           toBeDeleted: false,
           position: 2
         },
         2:{
           id : 2,
           name: 'John',
           age: 45,
           toBeDeleted: true,
           position: 3
         },
         3:{
           id : 3,
           name: 'Paul',
           age: 65,
           toBeDeleted: false,
           position: 1
         }
       ];

I try this way, but it doesn't work :

   const sorted = Object.values(people)
       .filter((people) => people.toBeDeleted !== true)
       .sort((a, b) => a.position - b.position);

If I delete the id keys, then my code works.

In result must be array like this :

   const people = [
         {
           id : 3,
           name: 'Paul',
           age: 65,
           toBeDeleted: false,
           position: 1
         },
         {
           id : 1,
           name: 'James',
           age: 31,
           toBeDeleted: false,
           position: 2
         }
       ];

the id keys are used in the project to select the necessary records, so I can't delete them



from Recent Questions - Stack Overflow https://ift.tt/3BouvFZ
https://ift.tt/eA8V8J

No comments:

Post a Comment