I\'m having trouble looping through an object and changing all the values to something else, let\'s say I want to change all the values to the string \"redacted\". I need to
Use a proxy:
function superSecret(spy) {
return new Proxy(spy, { get() { return "redacted"; } });
}
> superSecret(spy).id
< "redacted"
You can also go functional.
Using Object.keys
is better as you will only go through the object properties and not it's prototype chain.
Object.keys(spy).reduce((acc, key) => {acc[key] = 'redacted'; return acc; }, {})
This version is more simple:
Object.keys(spy).forEach(key => {
spy[key] = "redacted");
});
try
var superSecret = function(spy){
Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });
return spy;
}
A nice solution is using a combination of Object.keys and reduce - which doesn't alter the original object;
var superSecret = function(spy){
return Object.keys(spy).reduce(
(attrs, key) => ({
...attrs,
[key]: 'redacted',
}),
{}
);
}
var superSecret = function(spy){
for(var key in spy){
if(spy.hasOwnProperty(key)){
//code here
spy[key] = "redacted";
}
}
return spy;
}