Object property names javascript

Object.getOwnPropertyNames()

The Object.getOwnPropertyNames() static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.

Try it

Syntax

Parameters

The object whose enumerable and non-enumerable properties are to be returned.

Return value

An array of strings that corresponds to the properties found directly in the given object.

Description

Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj . The ordering of the enumerable properties in the array is consistent with the ordering exposed by a for. in loop (or by Object.keys() ) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion.

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError . In ES2015, a non-object argument will be coerced to an object.

.getOwnPropertyNames("foo"); // TypeError: "foo" is not an object (ES5 code) Object.getOwnPropertyNames("foo"); // ["0", "1", "2", "length"] (ES2015 code) 

Examples

Using Object.getOwnPropertyNames()

const arr = ["a", "b", "c"]; console.log(Object.getOwnPropertyNames(arr).sort()); // ["0", "1", "2", "length"] // Array-like object const obj =  0: "a", 1: "b", 2: "c" >; console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"] Object.getOwnPropertyNames(obj).forEach((val, idx, array) =>  console.log(`$val> -> $obj[val]>`); >); // 0 -> a // 1 -> b // 2 -> c // non-enumerable property const myObj = Object.create( >,  getFoo:  value()  return this.foo; >, enumerable: false, >, >, ); myObj.foo = 1; console.log(Object.getOwnPropertyNames(myObj).sort()); // ["foo", "getFoo"] 

If you want only the enumerable properties, see Object.keys() or use a for. in loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with hasOwn() ).

Items on the prototype chain are not listed:

function ParentClass() > ParentClass.prototype.inheritedMethod = function () >; function ChildClass()  this.prop = 5; this.method = function () >; > ChildClass.prototype = new ParentClass(); ChildClass.prototype.prototypeMethod = function () >; console.log(Object.getOwnPropertyNames(new ChildClass())); // ["prop", "method"] 

Get non-enumerable properties only

This uses the Array.prototype.filter() function to remove the enumerable keys (obtained with Object.keys() ) from a list of all keys (obtained with Object.getOwnPropertyNames() ) thus giving only the non-enumerable keys as output.

const target = myObject; const enumAndNonenum = Object.getOwnPropertyNames(target); const enumOnly = new Set(Object.keys(target)); const nonenumOnly = enumAndNonenum.filter((key) => !enumOnly.has(key)); console.log(nonenumOnly); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Object.getOwnPropertyNames()

Метод Object.getOwnPropertyNames() возвращает массив всех свойств (включая неперечислимые свойства, кроме тех, которые используют символ), найденных непосредственно в данном объекте.

Try it

Syntax

Object.getOwnPropertyNames(obj)

Parameters

Объект,перечисляемые и неперечисляемые свойства которого должны быть возвращены.

Return value

Массив строк,соответствующий свойствам,найденным непосредственно в данном объекте.

Description

Object.getOwnPropertyNames() возвращает массив, элементами которого являются строки, соответствующие перечислимым и неперечисляемым свойствам, найденным непосредственно в данном объекте obj . Порядок перечисляемых свойств в массиве согласуется с порядком, предоставляемым циклом for. in (или Object.keys() ) по свойствам объекта. Неотрицательные целые ключи объекта (как перечисляемые, так и неперечислимые) добавляются в массив в порядке возрастания первыми, а затем строковые ключи в порядке вставки.

В ES5, если аргумент этого метода не является объектом (примитивом), это вызовет TypeError . В ES2015 аргумент, не являющийся объектом, будет приведен к объекту.

Object.getOwnPropertyNames('foo'); // TypeError: "foo" is not an object (ES5 code) Object.getOwnPropertyNames('foo'); // ["0", "1", "2", "length"] (ES2015 code)

Examples

Using Object.getOwnPropertyNames()

const arr = ['a', 'b', 'c']; console.log(Object.getOwnPropertyNames(arr).sort()); // .sort () - это метод массива. // журналы ["0", "1", "2", "длина"] // Объект в виде массива const obj = < 0: 'a', 1: 'b', 2: 'c' >; console.log(Object.getOwnPropertyNames(obj).sort()); // .sort () - это метод массива. // журналы ["0", "1", "2"] //Регистрация имен и значений свойств с помощью forEach() Object.getOwnPropertyNames(obj).forEach((val, idx, array) => < console.log(`$ -> $ `); >); // logs // 0 -> а // 1 -> b // 2 -> c // неперечислимое свойство const myObj = Object.create(<>, < getFoo: < value( ) < return this.foo; >, enumerable: false, > >); myObj.foo = 1; console.log(Object.getOwnPropertyNames(my_obj).sort()); // журналы ["foo", "getFoo"] 

Если вам нужны только перечисляемые свойства, см. Object.keys() или используйте цикл for. in (обратите внимание, что это также вернет перечисляемые свойства, найденные в цепочке прототипов для объекта, если последний не отфильтрован с помощью hasOwn() ) .

Пункты в цепи прототипов не указаны:

function ParentClass( ) <> ParentClass.prototype.inheritedMethod = function ( ) <>; function ChildClass( ) < this.prop = 5; this.method = function ( ) <>; > ChildClass.prototype = new ParentClass; ChildClass.prototype.prototypeMethod = function ( ) <>; console.log(Object.getOwnPropertyNames(new ChildClass())); // ["опора", "метод"] 

Получить только неперечисляемые свойства

Здесь используется Array.prototype.filter() для удаления перечислимых ключей (полученных с помощью Object.keys() ) из списка всех ключей (полученных с помощью Object.getOwnPropertyNames() ), что дает только неперечислимые ключи в качестве вывода. .

const target = myObject; const enumAndNonenum = Object.getOwnPropertyNames(target); const enumOnly = new Set(Object.keys(target)); const nonenumOnly = enumAndNonenum.filter((key) => !enumOnly.has(key)); console.log(nonenumOnly);

Specifications

Источник

How to List the Properties of a JavaScript Object

In this tutorial, two mostly used methods are presented, which will list the properties of a JavaScript object.

You can use the built-in Object.keys method which is supported in the modern browsers:

let keys = Object.keys(myObj);

Example:

w3docs logo

Javascript Object.keys method

To retrieve the list of the property names, you can do the following:

let getKeys = function (obj) < let keysArr = []; for (var key in obj) < keysArr.push(key); >return keysArr; >

Example:

w3docs logo

Javascript object list of the property names

Alternatively, you can replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. However, extending the prototype has some side effects and is not recommended.

You can also use the for. in construct to iterate over an object for its attribute names. However, doing it, you will iterate over all attribute names in the object’s prototype chain. To iterate only over the attributes of the object, you can use the hasOwnProperty() method like this:

for (var key in obj) < if (obj.hasOwnProperty(key)) < /* code here */ > >

Example:

w3docs logo

Javascript object hasOwnProperty() method

The Object.keys() method

The Object.keys() method returns the array of a specified object’s own enumerable property names. The property order is the same as in the case of looping over the properties of the object manually.

The hasOwnProperty() Method

The hasOwnProperty() method returns a boolean value that indicates if the object has the specified property as its own property or not. If the object contains the «key» property, a function is created. This would return true if it could find no keys in the loop, meaning the object is empty. If any key is found, the loop breaks returning false.

Источник

Читайте также:  Как в css unlimited
Оцените статью