如果有一个Javascript对象:
var objects={...};
假设它有50多个属性,却不知道属性名称(即不知道“键”)如何在循环中获取每个属性值?
如果有一个Javascript对象:
var objects={...};
假设它有50多个属性,却不知道属性名称(即不知道“键”)如何在循环中获取每个属性值?
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])
})
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])
var objects={...}; this.getAllvalues = function () {
var vls = [];
for (var key in objects) {
vls.push(objects[key]);
}
return vls;
}
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
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]];
}
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!
ES5 Object.keys
var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]
您可以循环浏览以下按键:
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
如果可以访问Underscore.js,则可以使用以下_.values
函数:
_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]
这是一个可重用的函数,用于将值放入数组。它也考虑了原型。
Object.values = function (obj) {
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
}
如果您真的想要一个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的键。
通过使用一个简单的for..in
循环:
for(var key in objects) {
var value = objects[key];
}
use
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console