您可以使用几个函数来获取所需的数据。
Object.keys()
此函数将返回所有可枚举、拥有属性非符号。
> let person = {name: 'John Doe', age: 25, [Symbol('Test')] : 'value'}
> Object.keys(person);
['name'] // Note that the Symbol('Test') is not in the returned array!
Object.getOwnPropertyNames()
此函数将返回所有 enumerable 和 non-enumerable 都是 非 符号的属性。
> Object.getOwnPropertyNames(Set)
[ 'length', 'name', 'prototype' ]
为什么我们有Object.keys()这个函数有用?
> Object.keys(Set)
[] // Because keys doesn't give you non-enumerable properies
顺便说一句,为什么Object.getOwnPropertyNames(Set) 没有像add、has 等提供Set 上的方法?因为他们在Set.prototype。 Object.getOwnPropertyNames(Set.prototype) 会产生更好的结果。
Object.getOwnPropertySymbols()
这将返回您传递给它的对象中的所有 拥有 属性,这些属性是 Symbols。
> let person = {x: 10, Symbol('Test'): 'Test-value' };
> Object.getOwnPropertySymbols(person);
[Symbol(Test)]
Reflect.ownKeys()
这将返回您传递给的对象中的所有拥有属性,这些属性是字符串/符号。
> let person = {x: 1, [Symbol('Test')]: 'Test-value'};
> Reflect.ownKeys(person);
[ 'x', Symbol(Test) ]
奖励:
Object.getPrototypeOf()
这将返回传递给它的 Object 的 Prototype。
> let nameable = { name: 'name' };
> let ageable = Object.create(nameable);
> ageable.age = 0;
> let person = Object.create(ageable);
> let proto_of_person = Object.getPrototypeOf(person);
> proto_of_person === ageable;
true
> let proto_of_ageable = Object.getPrototypeOf(proto_of_person);
> proto_of_ageable === nameable
true
使用它,我们可以递归地枚举对象及其原型链的所有属性。