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:07

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

_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]
查看更多
素衣白纱
3楼-- · 2018-12-31 04:07

I realize I'm a little late but here's a shim for the new firefox 47 Object.values method

Object.prototype.values = Object.prototype.values || function(obj) {
  return this.keys(obj).map(function(key){
    return obj[key];
  });
};
查看更多
闭嘴吧你
4楼-- · 2018-12-31 04:10

Here's a function similar to PHP's array_values()

function array_values(input) {
  var output = [], key = '';
  for ( key in input ) { output[output.length] = input[key]; }
  return output;
}

Here's how to get the object's values if you're using ES6 or higher:

Array.from(values(obj));
查看更多
一个人的天荒地老
5楼-- · 2018-12-31 04:10

Object.entries do it in better way.

  var dataObject = {"a":{"title":"shop"}, "b":{"title":"home"}}
 
   Object.entries(dataObject).map(itemArray => { 
     console.log("key=", itemArray[0], "value=", itemArray[1])
  })

查看更多
浮光初槿花落
6楼-- · 2018-12-31 04:11

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

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.

查看更多
无与为乐者.
7楼-- · 2018-12-31 04:12

By using a simple for..in loop:

for(var key in objects) {
    var value = objects[key];
}
查看更多
登录 后发表回答