Looping through an object and changing all values

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.

Answers:

Answer

try

var superSecret = function(spy){
  Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });
  return spy;
}
Answer

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

Answer
var superSecret = function(spy){
    for(var key in spy){
          if(spy.hasOwnProperty(key)){
               //code here
               spy[key] = "redacted"; 
            }
     }
   return spy;    
}
Answer

I wrote a little helper function that walks through an object and applies a callback to each entry:

iterateEntries(node, fn) {
    const newNode = {};
    Object.entries(node).forEach(([key, val]) => (newNode[key] = fn(val)));
    return newNode;
}

Usage:

iterateEntries(yourObject, (entry) => {
  return entry; // do something with entry here
});
Answer

Use a proxy:

function superSecret(spy) {
  return new Proxy(spy, { get() { return "redacted"; } });
}

> superSecret(spy).id
< "redacted"
Answer

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

This version is more simple:

  Object.keys(spy).forEach(key => {
    spy[key] = "redacted");
  });

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.