如果有JavaScript对象:
var objects={...};
假设,它有超过50个属性,不知道属性名称(即不知道“键”)如何在循环中获得每个属性值?
如果有JavaScript对象:
var objects={...};
假设,它有超过50个属性,不知道属性名称(即不知道“键”)如何在循环中获得每个属性值?
当前回答
const object1 = {
a: 'somestring',
b: 42
};
for (let [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed
其他回答
这个问题没有指定是否也需要继承的和不可枚举的属性。
获得谷歌不容易找到的所有东西,包括继承的属性和不可枚举的属性,都存在一个问题。
如果我们要获得所有继承的和不可枚举的属性,我的解决方案是:
function getAllPropertyNames(obj) {
let result = new Set();
while (obj) {
Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
obj = Object.getPrototypeOf(obj);
}
return [...result];
}
然后遍历它们,只需要使用for-of循环:
函数getAllPropertyNames(obj) { let result = new Set(); While (obj) { Object.getOwnPropertyNames (obj)。forEach(p => result.add(p)); obj = Object.getPrototypeOf(obj); } 返回结果[…]; } 让obj = { 美国广播公司(abc): 123, 某某:1.234, foobar:“你好” }; for (p of getAllPropertyNames(obj)) console.log(p);
const myObj = {a:1, b:2, c:3}
获取所有值:
最短的方法: 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;
}
下面是一个类似于PHP的array_values()函数
function array_values(input) {
var output = [], key = '';
for ( key in input ) { output[output.length] = input[key]; }
return output;
}
如果你使用ES6或更高版本,下面是如何获取对象的值:
Array.from(values(obj));
通过使用简单的for..in循环:
for(var key in objects) {
var value = objects[key];
}