Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a key value pair on each user object

Tags:

javascript

I am having difficulty deleting key-value pairs on each user object

I have been using the delete method to try to delete the password object as so return delete Object.keys(users.password)

function deleteManyPasswords(users) {
  /*
    This function take an array of user objects and deletes the password key value pair on each user object.
    E.g.
    [
      {name: 'Barry', password: 'ilovetea'},
      {name: 'Sandeep', password: 'ilovecoffee'},
      {name: 'Kavita', password: 'ilovepie'}
    ]
    Returns:
    [
      {name: 'Barry' },
      {name: 'Sandeep'},
      {name: 'Kavita'}
    ]
  */
like image 640
Rowandinho Avatar asked Oct 14 '25 02:10

Rowandinho


2 Answers

You can use map() with destructuring. Destructure the properties you want to remove and return the rest properties from map()

const arr = [ {name: 'Barry', password: 'ilovetea'}, {name: 'Sandeep', password: 'ilovecoffee'}, {name: 'Kavita', password: 'ilovepie'} ]

function deletePass(arr){
  return arr.map(({password,...rest}) => rest)
}
console.log(deletePass(arr))

The above method doesn't work for dynamic properties because you can't name all the properties. For that you can use the following way]

  • Create a function which takes two function.
    • An array of object
    • An array which contain keys which should be removed.
  • Use the map() function on the array.
  • Get the entries of each object using Object.entries()
  • Use filter() on entries and check if key is not present in the keys to be removed then remove it
  • Use Object.fromEntries() on the filtered entries and you will get the result array of objects.

const arr = [ {name: 'Barry', password: 'ilovetea'}, {name: 'Sandeep', password: 'ilovecoffee'}, {name: 'Kavita', password: 'ilovepie'} ]

function deleteProps(arr,keys){
   return arr.map(x => 
               Object.fromEntries(
                  Object.entries(x)
                  .filter(([k]) => !keys.includes(k))
               )
            )
}
console.log(deleteProps(arr,["password"]))
like image 119
Maheer Ali Avatar answered Oct 16 '25 15:10

Maheer Ali


You could remove an attribute by using delete Key.
Have a look below.

var data =[
    {name: 'Barry', password: 'ilovetea'},
    {name: 'Sandeep', password: 'ilovecoffee'},
    {name: 'Kavita', password: 'ilovepie'}
]

function removeKey(items, key){

    items.forEach(item=> {
        delete item[key]; // remove the attr eg Password
    });

    return items;
}

console.log(removeKey(data, "password"))
like image 24
Alen.Toma Avatar answered Oct 16 '25 17:10

Alen.Toma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!