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 be able to do this in pure JavaScript.
For example I'd have an object like this...
spy = { id: 007, name: "James Bond", age: 31 };
and the object would look like this after...
spy = { id: "redacted", name: "redacted", age: "redacted" };
Here is what I have to start with
var superSecret = function(spy){ // Code Here }
This shouldn't create a new spy object but update it.
Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.
Description. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).
try
var superSecret = function(spy){ Object.keys(spy).forEach(function(key){ spy[key] = "redacted" }); return spy; }
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; }, {})
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