How to get all properties values of a Javascript O

2018-12-31 03:35发布

If there is an Javascript object:

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?

20条回答
柔情千种
2楼-- · 2018-12-31 04:12

Now I use Dojo Toolkit because older browsers do not support Object.values.

require(['dojox/lang/functional/object'], function(Object) {
    var obj = { key1: '1', key2: '2', key3: '3' };
    var values = Object.values(obj);
    console.log(values);
});

Output :

['1', '2', '3']
查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 04:16

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
查看更多
大哥的爱人
4楼-- · 2018-12-31 04:19

Compatible with ES7 even some browsers do not support it yet

Since , Object.values(<object>) will be built-in in ES7 &

Until waiting all browsers to support it , you could wrap it inside a function :

Object.vals=(o)=>(Object.values)?Object.values(o):Object.keys(o).map((k)=>o[k])

Then :

Object.vals({lastname:'T',firstname:'A'})
 // ['T','A']

Once browsers become compatible with ES7, you will not have to change anything in your code.

查看更多
零度萤火
5楼-- · 2018-12-31 04:21

Apparently - as I recently learned - this is the fastest way to do it:

var objs = {...};
var objKeys = Object.keys(obj);
for (var i = 0, objLen = objKeys.length; i < objLen; i++) {
    // do whatever in here
    var obj = objs[objKeys[i]];
}
查看更多
刘海飞了
6楼-- · 2018-12-31 04:22

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;
}
查看更多
浮光初槿花落
7楼-- · 2018-12-31 04:22

in ECMAScript5 use

 keys = Object.keys(object);

Otherwise if you're browser does not support it, use the well-known for..in loop

for (key in object) {
    // your code here
}
查看更多
登录 后发表回答