如何获取 JavaScript 对象的所有属性值(不知道键)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7306669/
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-24 01:42:27  来源:igfitidea点击:

How to get all properties values of a JavaScript Object (without knowing the keys)?

javascriptjavascript-objects

提问by Mellon

If there is an Javascript object:

如果有一个 Javascript 对象:

var objects={...};

Suppose, it has more than 50 properties, without knowing the property names (that's without knowing the 'keys') how to get each property value in a loop?

假设,它有 50 多个属性,不知道属性名称(即不知道“键”)如何在循环中获取每个属性值?

采纳答案by Tatu Ulmanen

By using a simple for..inloop:

通过使用一个简单的for..in循环:

for(var key in objects) {
    var value = objects[key];
}

回答by qubyte

Depending on which browsers you have to support, this can be done in a number of ways. The overwhelming majority of browsers in the wild support ECMAScript 5 (ES5), but be warned that many of the examples below use Object.keys, which is not available in IE < 9. See the compatibility table.

根据您必须支持的浏览器,这可以通过多种方式完成。绝大多数浏览器都支持 ECMAScript 5 (ES5),但请注意,下面的许多示例都使用Object.keysIE < 9 中不可用的 。请参阅兼容性表

ECMAScript 3+

ECMAScript 3+

If you have to support older versions of IE, then this is the option for you:

如果您必须支持旧版本的 IE,那么这是您的选择:

for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var val = obj[key];
        // use val
    }
}

The nested ifmakes sure that you don't enumerate over properties in the prototype chain of the object (which is the behaviour you almost certainly want). You must use

嵌套if确保您不会枚举对象原型链中的属性(这几乎肯定是您想要的行为)。你必须使用

Object.prototype.hasOwnProperty.call(obj, key) // ok

rather than

而不是

obj.hasOwnProperty(key) // bad

because ECMAScript 5+ allows you to create prototypeless objects with Object.create(null), and these objects will not have the hasOwnPropertymethod. Naughty code might also produce objects which override the hasOwnPropertymethod.

因为 ECMAScript 5+ 允许您使用 来创建无原型对象Object.create(null),而这些对象将没有该hasOwnProperty方法。顽皮的代码也可能产生覆盖hasOwnProperty方法的对象。

ECMAScript 5+

ECMAScript 5+

You can use these methods in any browser that supports ECMAScript 5 and above. These get values from an object and avoid enumerating over the prototype chain. Where objis your object:

您可以在任何支持 ECMAScript 5 及更高版本的浏览器中使用这些方法。这些从对象中获取值并避免在原型链上进行枚举。obj你的对象在哪里:

var keys = Object.keys(obj);

for (var i = 0; i < keys.length; i++) {
    var val = obj[keys[i]];
    // use val
}

If you want something a little more compact or you want to be careful with functions in loops, then Array.prototype.forEachis your friend:

如果你想要更紧凑的东西或者你想要小心循环中的函数,那么Array.prototype.forEach你的朋友:

Object.keys(obj).forEach(function (key) {
    var val = obj[key];
    // use val
});

The next method builds an array containing the values of an object. This is convenient for looping over.

下一个方法构建一个包含对象值的数组。这便于循环。

var vals = Object.keys(obj).map(function (key) {
    return obj[key];
});

// use vals array

If you want to make those using Object.keyssafe against null(as for-inis), then you can do Object.keys(obj || {})....

如果你想让那些使用Object.keys安全对抗null(原样for-in),那么你可以做Object.keys(obj || {})....

Object.keysreturns enumerableproperties. For iterating over simple objects, this is usually sufficient. If you have something with non-enumerable properties that you need to work with, you may use Object.getOwnPropertyNamesin place of Object.keys.

Object.keys返回可枚举的属性。对于迭代简单的对象,这通常就足够了。如果您在使用非枚举的属性,你需要工作的东西,你可以使用Object.getOwnPropertyNames代替Object.keys

ECMAScript 2015+ (A.K.A. ES6)

ECMAScript 2015+(又名 ES6)

Arrays are easier to iterate with ECMAScript 2015. You can use this to your advantage when working with values one-by–one in a loop:

使用 ECMAScript 2015 更容易迭代数组。在循环中逐个处理值时,您可以利用它来发挥自己的优势:

for (const key of Object.keys(obj)) {
    const val = obj[key];
    // use val
}

Using ECMAScript 2015 fat-arrow functions, mapping the object to an array of values becomes a one-liner:

使用 ECMAScript 2015 粗箭头函数,将对象映射到值数组成为单行:

const vals = Object.keys(obj).map(key => obj[key]);

// use vals array

ECMAScript 2015 introduces Symbol, instances of which may be used as property names. To get the symbols of an object to enumerate over, use Object.getOwnPropertySymbols(this function is why Symbolcan'tbe used to make private properties). The new ReflectAPI from ECMAScript 2015 provides Reflect.ownKeys, which returns a list of property names (including non-enumerable ones) and symbols.

ECMAScript 2015 引入了Symbol,其实例可用作属性名称。要获取要枚举的对象的符号,请使用Object.getOwnPropertySymbols(此函数是为什么Symbol不能用于创建私有属性的原因)。ReflectECMAScript 2015的新API 提供了Reflect.ownKeys,它返回属性名称(包括不可枚举的)和符号的列表。

Array comprehensions (do not attempt to use)

数组推导式(不要尝试使用)

Array comprehensions were removedfrom ECMAScript 6 before publication. Prior to their removal, a solution would have looked like:

数组推导式在发布之前已从 ECMAScript 6中删除。在删除之前,解决方案看起来像:

const vals = [for (key of Object.keys(obj)) obj[key]];

// use vals array

ECMAScript 2017+

ECMAScript 2017+

ECMAScript 2016 adds features which do not impact this subject. The ECMAScript 2017 specification adds Object.valuesand Object.entries. Both return arrays (which will be surprising to some given the analogy with Array.entries). Object.valuescan be used as is or with a for-ofloop.

ECMAScript 2016 添加了不影响本主题的功能。ECMAScript 2017 规范添加了Object.valuesObject.entries. 两个都返回数组(考虑到与 的类比,这会让某些人感到惊讶Array.entries)。Object.values可以按原样使用或与for-of循环一起使用。

const values = Object.values(obj);

// use values array or:

for (const val of Object.values(obj)) {
    // use val
}

If you want to use both the key and the value, then Object.entriesis for you. It produces an array filled with [key, value]pairs. You can use this as is, or (note also the ECMAScript 2015 destructuring assignment) in a for-ofloop:

如果您想同时使用键和值,那么Object.entries适合您。它产生一个充满[key, value]对的数组。您可以按原样使用它,或者(还请注意 ECMAScript 2015 解构赋值)在for-of循环中使用:

for (const [key, val] of Object.entries(obj)) {
    // use key and val
}

Object.valuesshim

Object.values垫片

Finally, as noted in the comments and by teh_senaus in another answer, it may be worth using one of these as a shim. Don't worry, the following does not change the prototype, it just adds a method to Object(which is much less dangerous). Using fat-arrow functions, this can be done in one line too:

最后,正如评论中和 teh_senaus 在另一个答案中所指出的,使用其中一个作为垫片可能是值得的。不用担心,下面没有改变原型,它只是添加了一个方法Object(危险性要小得多)。使用胖箭头函数,这也可以在一行中完成:

Object.values = obj => Object.keys(obj).map(key => obj[key]);

which you can now use like

你现在可以使用像

// ['one', 'two', 'three']
var values = Object.values({ a: 'one', b: 'two', c: 'three' });

If you want to avoid shimming when a native Object.valuesexists, then you can do:

如果您想在本地Object.values存在时避免填充,则可以执行以下操作:

Object.values = Object.values || (obj => Object.keys(obj).map(key => obj[key]));

Finally...

最后...

Be aware of the browsers/versions you need to support. The above are correct where the methods or language features are implemented. For example, support for ECMAScript 2015 was switched off by default in V8 until recently, which powered browsers such as Chrome. Features from ECMAScript 2015 should be be avoided until the browsers you intend to support implement the features that you need. If you use babelto compile your code to ECMAScript 5, then you have access to all the features in this answer.

请注意您需要支持的浏览器/版本。在实现方法或语言功能的地方,以上是正确的。例如,直到最近,V8 才默认关闭对 ECMAScript 2015 的支持,这为 Chrome 等浏览器提供了动力。在您打算支持的浏览器实现您需要的功能之前,应避免使用 ECMAScript 2015 中的功能。如果您使用babel将代码编译为 ECMAScript 5,那么您就可以访问此答案中的所有功能。

回答by teh_senaus

Here's a reusable function for getting the values into an array. It takes prototypes into account too.

这是一个可重用的函数,用于将值放入数组中。它也考虑到原型。

Object.values = function (obj) {
    var vals = [];
    for( var key in obj ) {
        if ( obj.hasOwnProperty(key) ) {
            vals.push(obj[key]);
        }
    }
    return vals;
}

回答by jichi

If you have access to Underscore.js, you can use the _.valuesfunction like this:

如果您有权访问 Underscore.js,则可以使用如下_.values函数:

_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]

回答by zzz

If you really want an array of Values, I find this cleaner than building an array with a for ... in loop.

如果你真的想要一个值数组,我发现这比用 for ... in 循环构建数组更干净。

ECMA 5.1+

ECMA 5.1+

function values(o) { return Object.keys(o).map(function(k){return o[k]}) }

It's worth noting that in most cases you don't really need an array of values, it will be faster to do this:

值得注意的是,在大多数情况下,您并不真正需要一组值,这样做会更快:

for(var k in o) something(o[k]);

This iterates over the keys of the Object o. In each iteration k is set to a key of o.

这将遍历 Object o 的键。在每次迭代中,k 被设置为 o 的键。

回答by MrBii

ES5 Object.keys

ES5 Object.keys

var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]

回答by ariera

You can loop through the keys:

您可以遍历键:

foo = {one:1, two:2, three:3};
for (key in foo){
    console.log("foo["+ key +"]="+ foo[key]);
}

will output:

将输出:

foo[one]=1
foo[two]=2
foo[three]=3

回答by Ch.Idea

For those early adapting people on the CofeeScript era, here's another equivalent for it.

对于那些早期适应 CofeeScript 时代的人来说,这里有另一个等价物。

val for key,val of objects

Which may be better than this because the objectscan be reduced to be typed again and decreased readability.

这可能比这更好,因为objects可以减少再次输入并降低可读性。

objects[key] for key of objects

回答by user40521

use a polyfill like:

使用 polyfill,如:

if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}

then use

然后使用

Object.values(my_object)

3) profit!

3)利润!

回答by ishandutta2007

ECMA2017 onwards:

ECMA2017 起:

Object.values(obj)will fetch you all the property values as an array.

Object.values(obj)将以数组的形式获取所有属性值。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values