Javascript 循环遍历对象并更改所有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36467369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:07:33  来源:igfitidea点击:

Looping through an object and changing all values

javascript

提问by Dominic

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.

我在遍历一个对象并将所有值更改为其他值时遇到问题,假设我想将所有值更改为字符串“redacted”。我需要能够在纯 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.

这不应该创建一个新的间谍对象,而是更新它。

回答by gurvinder372

try

尝试

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

回答by Sol

You can also go functional.

你也可以去实用。

Using Object.keysis better as you will only go through the object properties and not it's prototype chain.

使用Object.keys更好,因为您只会浏览对象属性而不是它的原型链。

Object.keys(spy).reduce((acc, key) => {acc[key] = 'redacted'; return acc; }, {})

Object.keys(spy).reduce((acc, key) => {acc[key] = 'redacted'; return acc; }, {})

回答by Himanshu Tanwar

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

回答by Lukas

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

回答by brandonlabs

A nice solution is using a combination of Object.keysand reduce- which doesn't alter the original object;

一个不错的解决方案是使用Object.keysreduce的组合——它不会改变原始对象;

var superSecret = function(spy){
  return Object.keys(spy).reduce(
    (attrs, key) => ({
      ...attrs,
      [key]: 'redacted',
    }),
    {}
  );
}

回答by Lgomes_dev

This version is more simple:

这个版本更简单:

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

回答by Lgomes_dev

Use a proxy:

使用代理:

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

> superSecret(spy).id
< "redacted"