遍历对象并更改所有值 [英] Looping through an object and changing all values

查看:78
本文介绍了遍历对象并更改所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在遍历一个对象并将所有值更改为其他值时遇到麻烦,比如说我想将所有值更改为已编辑"字符串.我需要能够使用纯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;
}

这篇关于遍历对象并更改所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆