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

如果有一个Javascript对象:

var objects={...};

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

GOHarry猪猪2020/03/13 18:19:58

use

console.log(variable)

and if you using google chrome open Console by using Ctrl+Shift+j

Goto >> Console

JinJin乐2020/03/13 18:19:58

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

乐泡芙2020/03/13 18:19:58

const myObj = { a:1, b:2, c:3 }

Get all values:

  • the shortest way:

    • const myValues = Object.values(myObj)
  • const myValues = Object.keys(myObj).map(key => myObj[key])

木心小哥2020/03/13 18:19:58
var objects={...}; this.getAllvalues = function () {
        var vls = [];
        for (var key in objects) {
            vls.push(objects[key]);
        }
        return vls;
    }
Tom凯飞云2020/03/13 18:19:58

ECMA2017 onwards:

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

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

2020/03/13 18:19:58

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]];
}
卡卡西Near2020/03/13 18:19:58

use a polyfill like:

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

then use

Object.values(my_object)

3) profit!

小小Eva2020/03/13 18:19:58

ES5 Object.keys

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

您可以循环浏览以下按键:

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

将输出:

foo[one]=1
foo[two]=2
foo[three]=3
蛋蛋蛋蛋2020/03/13 18:19:58

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

_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]
小卤蛋Tony2020/03/13 18:19:58

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

Object.values = function (obj) {
    var vals = [];
    for( var key in obj ) {
        if ( obj.hasOwnProperty(key) ) {
            vals.push(obj[key]);
        }
    }
    return vals;
}
飞云斯丁GO2020/03/13 18:19:58

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

ECMA 5.1+

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

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

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

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

A十三2020/03/13 18:19:58

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

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