56

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.

1
  • 1
    You can use Object.keys(spy) to get the property names, then loop over that using say forEach. Lots of questions and answers here on that.
    – RobG
    Apr 7, 2016 at 5:30

10 Answers 10

83

try

var superSecret = function(spy){
  Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });
  return spy;
}
8
  • 1
    Man giving me an error of function returned undefined :(
    – Dominic
    Apr 7, 2016 at 5:32
  • 2
    Just return spy;
    – Rayon
    Apr 7, 2016 at 5:32
  • Just face palmed myself. I appreciate the help! Been a while since I've played with JavaScript.
    – Dominic
    Apr 7, 2016 at 5:34
  • @RayonDabre thanks, though OP gave no indication of whether he wants to use the retured value :) Apr 7, 2016 at 5:42
  • @gurvinder372, My comment was for OP as he was expecting something in return ;)
    – Rayon
    Apr 7, 2016 at 5:44
30

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

1
  • 2
    To extend this to altering the values in the starting object (eg, adding 1 to each value if the values are numbers), change acc[key] = 'redacted' to acc[key] = spy[key] + 1. Mar 10, 2019 at 12:35
15

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',
    }),
    {}
  );
}
1
  • Are there performance implications for copying the accumulator to a new object at each iteration? Seems like this could be done by preserving a single accumulator object throughout. Dec 22, 2021 at 19:57
10

Here is a more simple version:

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

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
});
1
  • 1
    This is better written than the accepted answer because it is not mutating the input of the function, instead creating a newNode Feb 16 at 17:05
5
var superSecret = function(spy){
    for(var key in spy){
          if(spy.hasOwnProperty(key)){
               //code here
               spy[key] = "redacted"; 
            }
     }
   return spy;    
}
1
  • I found this to be a most useful solution for my particular use case. Upvoted, thanks.
    – MarkA
    Oct 22, 2020 at 10:30
3

Old question but I see that the checked solution have some "problems", this is the one that should acutally work:

Object.keys(myArray).forEach(i => {myArray[i] = "redacted"})
0

Use a proxy:

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

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

You can change object values based condition

const user = {
    name: 'John Doe',
    email: 'john.doe@example.com',
};

// iterate over the user object

for (const key in user) {
   user.hasOwnProperty(key)? user[key] === 'John Doe'? user[key] = "ali" : false : false 
   console.log(`${key}: ${user[key]}`);
}
-2

let dataArray = [
            {
                total: 112,
                tax: 51,
                key:0,
            },
            {
                total: 58,
                tax: 53,
                key:0,
            }
        ];

dataArray.map((data, i) => {
   dataArray[i].key = data.total - data.tax;
});

console.log(dataArray);

1
  • It's not an array, it's an object
    – Sarah
    Jun 3, 2021 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.