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'}
]
*/
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]
map()
function on the array. Object.entries()
filter()
on entries and check if key is not present in the keys to be removed then remove itObject.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"]))
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With