如何通过键获取 Javascript 对象的所有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36884483/
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
How to get all values of a Javascript Object by its keys?
提问by Alessandro C
I have a Javascript object with some keys and values:
我有一个带有一些键和值的 Javascript 对象:
var obj = {
"key1" : "val1",
"key2" : "val2",
"key3" : "val3",
"key4" : ""
}
I want to iterate all keys and retrieving all values.
我想迭代所有键并检索所有值。
I tried 2 ways:
我尝试了两种方法:
1) Using for(var key in keys)
1) 使用 for(var key in keys)
var keys = Object.keys(obj);
for (var key in keys) {
// ...
}
The problem with this solution is that keys object is an array, so I have to use obj[keys[key]]]. Not very pretty.
这个解决方案的问题是keys对象是一个数组,所以我必须使用obj[keys[key]]]。不是很漂亮。
Furthermore, inspecting "key4", the return value is "0" instead of "" (empty).
此外,检查“key4”,返回值是“0”而不是“”(空)。
2) Using forEach
2) 使用 forEach
Object.keys(obj).forEach(function(key){
// ...
});
The problem in this case is that if I try to do:
在这种情况下的问题是,如果我尝试这样做:
Object.keys(obj).forEach(function(key){
obj[key]; // <- obj is undefined !!
});
The "obj" variable is undefined in the foreach!
“obj”变量在 foreach 中未定义!
What's the best way to iterate in all keys for retrieving all values?
迭代所有键以检索所有值的最佳方法是什么?
Thanks
谢谢
回答by T.J. Crowder
In your first example, you're using for-in
to loop through an array, which is not generally a good idea. To loop through arrays, this answerhas lots of options for you.
在您的第一个示例中,您使用for-in
循环遍历数组,这通常不是一个好主意。要遍历数组,此答案为您提供了很多选项。
If you want to loop through all of an object's keys, use for-in
on the object:
如果要遍历对象的所有键,请for-in
在对象上使用:
for (var key in obj) {
var value = obj[key];
// ...
}
Note that you'll see both the object's ownproperties and also ones it inherits from its prototype. If you just want ownproperties, you could add a guard:
请注意,您将看到对象自己的属性以及从其原型继承的属性。如果你只想要自己的属性,你可以添加一个守卫:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var value = obj[key];
// ...
}
}
...or use Object.keys
(introduced in ES5, in 2009, so not on IE8; there's a shim if you need to support obsolete browsers like IE8):
...或使用Object.keys
(在 2009 年在 ES5 中引入,因此不在 IE8 上;如果您需要支持过时的浏览器(如 IE8),则可以使用 shim):
Object.keys(obj).forEach(function(key) {
var value = obj[key];
// ...
});
In both cases, you'll only get the object's enumerableproperties. If you need to include non-enumerableproperties, reach for getOwnPropertyNames
:
在这两种情况下,您只会获得对象的可枚举属性。如果您需要包含不可枚举的属性,请访问getOwnPropertyNames
:
Object.getOwnPropertyNames(obj).forEach(function(key) {
var value = obj[key];
// ...
});
That will get the object's own (not inherited) property names, even if non-enumerable, as long as they're strings (which they always are in ES5 and earlier; in ES2015 and later, they're normally strings but can also be Symbol
instances if you use Symbol
s).
这将获得对象自己的(不是继承的)属性名称,即使是不可枚举的,只要它们是字符串(它们总是在 ES5 及更早版本中;在 ES2015 及更高版本中,它们通常是字符串,但也可以是Symbol
实例,如果您使用Symbol
s)。
getOwnPropertyNames
was also introduced in ES5, but I don't think it can be shimmed, so you can't use it in IE8 or other obsolete browsers.
getOwnPropertyNames
在 ES5 中也引入了,但我认为它不能被 shimmed,所以你不能在 IE8 或其他过时的浏览器中使用它。
回答by Ali Mamedov
Just use for in
.
只需使用for in
.
var obj = {
"key1" : "val1",
"key2" : "val2",
"key3" : "val3",
"key4" : ""
};
for (var key in obj) {
console.log(key); // key1 and etc...
console.log(obj[key]); // val1 and etc...
}
回答by Udhayha Karthik
Object.values()will provide an array of the objects property values.
Object.values()将提供对象属性值的数组。
const object1 = { a: 'somestring', b: 42, c: false };
console.log(Object.values(object1)); // expected output: Array
["somestring", 42, false]
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
回答by backslashN
Using ES6, Object.keys(obj).map(key => obj[key])
will return an array containing all the values.
使用 ES6,Object.keys(obj).map(key => obj[key])
将返回一个包含所有值的数组。
回答by Cris
It's strange that you have this problem of obj undefined, it shouldn't happens. Here it is another way to it, in addition of the other answers. It's useful only if you don't need filter something and you want just to have an array with all values (and few lines)
奇怪的是你有这个 obj undefined 的问题,它不应该发生。除了其他答案之外,这是另一种方式。仅当您不需要过滤某些东西并且只想拥有一个包含所有值(和几行)的数组时,它才有用
var values = []
Object.keys(object)
.every( (prop) => values.push(object[prop]))
回答by Lajos Arpad
I like the first approach much more than the second one, but there is no need to store the keys separately. Let's consider this example:
我比第二种方法更喜欢第一种方法,但是不需要单独存储密钥。让我们考虑这个例子:
function parseValues(obj, operation) {
for (key in obj) {
operation(obj[key], key);
}
}
As you can see we did not need to read the keys. You can use a function
like this for any purposes. For example:
如您所见,我们不需要读取密钥。您可以将function
类似的用于任何目的。例如:
var myObject = {a: 1, b: 2, c: 3};
parseValues(myObject, function(item, key) {
if (key !== "b") {
if (item > 1) {
myObject[key] = item * 2;
}
}
});
There are literally infinitely many ways you can use this like. In the second approach the forEach
runs for the keys and not for the object whose keys you are parsing. You need to use getOwnPropertyNames
, as T.J.Crowther has already pointed out.
从字面上看,您可以使用无限多种方式来使用它。在第二种方法中,forEach
运行的是键而不是您正在解析其键的对象。您需要使用getOwnPropertyNames
,正如 TJCrowther 已经指出的那样。