Remove all fields except some

Create a function, which removes all fields except ‘firstName’ and ‘lastName’ from the objects.

This is the code I’ve written. Any recommendations?

let people = [
    {
        firstName: 'John',
        lastName: 'Clark',
        gender: 'male'
    },
    {
        firstName: 'Kaily',
        lastName: 'Berserk',
        gender: 'female'
    },
    {
        firstName: 'Steven',
        lastName: 'Bergeron',
        gender: 'male'
    }
];

function removeAllExceptNames(arr) {
    let first = 'firstName';
    let last = 'lastName';

    return arr.forEach(p => {
        if (p !== first || p !== last) {
            delete arr[p];
        }
    })
}

console.log(removeAllExceptNames(people));
console.log(people);

Answer

I have 2 arguments in the function, the arr and the names

arr is the given array, names is the list of fields you want to keep in the array

I used forEach twice.. the first time was for the arr, the second time was for the Object’s keys for each index in arr and that is where the exception names can be related to fields in the array of objects

let people = [
    {
        firstName: 'John',
        lastName: 'Clark',
        gender: 'male'
    },
    {
        firstName: 'Kaily',
        lastName: 'Berserk',
        gender: 'female'
    },
    {
        firstName: 'Steven',
        lastName: 'Bergeron',
        gender: 'male'
    }
];

function removeAllExceptNames(arr,names) { //arr is the same, names is a list of names you want to keep
  arr.forEach(a=>{
    Object.keys(a).forEach(b=>{
      if(!names.includes(b)){delete(a[b])}
    })
  })
}

removeAllExceptNames(people,["firstName","lastName"]);
console.log(people);