Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through an object and changing all values

Tags:

javascript

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.

like image 776
Dominic Avatar asked Apr 07 '16 05:04

Dominic


People also ask

How do you loop through values of an object?

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.

What line of code is used to iterate through all the properties of an object?

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).


2 Answers

try

var superSecret = function(spy){   Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });   return spy; } 
like image 53
gurvinder372 Avatar answered Sep 21 '22 03:09

gurvinder372


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; }, {})

like image 31
Harshal Avatar answered Sep 21 '22 03:09

Harshal