遍历对象并更改所有值
问题描述:
我在遍历一个对象并将所有值更改为其他值时遇到麻烦,比如说我想将所有值更改为已编辑"字符串.我需要能够使用纯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"
};
这是我必须开始的
var superSecret = function(spy){
// Code Here
}
这不应创建新的间谍对象,而应对其进行更新.
This shouldn't create a new spy object but update it.
答
尝试
var superSecret = function(spy){
Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });
return spy;
}