Javascript getting all object properties

How to get all own properties of an object in JavaScript

To get all own properties of an object in JavaScript, you can use the Object.getOwnPropertyNames() method.

This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.

The Object.getOwnPropertyNames() method does not look for the inherited properties.

const user =  name: 'Alex', age: 30 > const props = Object.getOwnPropertyNames(user) console.log(props) // [ 'name', 'age' ] 

If you are interested in the own enumerable properties of the object, use the Object.keys() method instead:

const user =  name: 'Alex', age: 30 > const props = Object.keys(user) console.log(props) // [ 'name', 'age' ] 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

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.

Источник

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.

Источник

How to Get All Property Values of a JavaScript Object

To detect all the property values of object without knowing the key can be done in a number of ways depending on browsers. The majority of browsers support ECMAScript 5 (ES5). Let’s see what methods can be used for getting the property value based on different specifications.

ECMAScript 5+

You can use the methods below in the browsers supporting ECMAScript 5+. These methods detect values from an object and avoid enumerating over the prototype chain:

w3docs logo

Javascript detect values from an object

To make the code more compact, use the forEach:

w3docs logo

Javascript detect values from an object use forEach

The following method builds an array which contains object values:

w3docs logo

Javascript detect values from an object builds an array

To make those using Object.keys safe against null, then you can run:

w3docs logo

Javascript detect values from an object builds an array

Object.keys returns enumerable properties. Using Object.keys is usually effective for iterating over simple objects. If you have something with non-enumerable properties to work with, you can use:

Object.getOwnPropertyNames instead of Object.keys.

ECMAScript 2015+ ( ES6)

It is easier to iterate Arrays with ECMAScript 2015. You can use the following script when working with values one-by-one in a loop:

w3docs logo

Javascript detect values one-by-one from an object

To use ECMAScript 2015 fat-arrow functions and to map the object to an Array of values can become a one-liner code:

w3docs logo

Javascript detect values from an object

The ECMAScript 2015 specification introduces Symbol, instances of which can be used as property names. You can use the Object.getOwnPropertySymbols to get the symbols of an object to enumerate over. The new Reflect API from ECMAScript 2015 provides Reflect.ownKeys returning a list of property names and symbols.

Object.values

This just adds a method to object. Using fat-arrow functions can be a one-liner:

w3docs logo

Javascript detect values from an object using Object.values

Object.values = obj => Object.keys(obj).map(key => objJavascript getting all object properties); //which you can now use like // [‘one’, ‘two’, ‘three’] let values = Object.values(< a: 'one', b: 'two', c: 'three' >); console.log(values);

If you do not want to use shimming when a native Object.values exists, then you can run:

w3docs logo

Javascript detect values from an object using Object.values

Object.values = Object.values || (obj => Object.keys(obj).map(key => objJavascript getting all object properties)); let values = Object.values(< a: 'one', b: 'two', c: 'three' >); console.log(values);

ECMAScript 2017+

This specification adds Object.values and Object.entries where both return arrays. Object.values can be used with a for-of loop:

w3docs logo

Javascript detect values from an object used Object.values

If you want to use both the key and the value, then you can use the Object.entries:

w3docs logo

Javascript detect values from an object used Object.entries

Object.keys/values/entries methods have similarity with for..in loop. They all ignore properties that apply Symbol(. ) as a key. When you need symbols, you can use a separate method Object.getOwnPropertySymbols which returns an array consisting of only symbolic keys.

BookDuck

  • How to Count the Number if Keys/Properties of a JavaScript object
  • How to Check for the Existence of Nested JavaScript Object Key
  • How to Check if an Object has a Specific Property in JavaScript
  • How to Loop Through or Enumerate a JavaScript Object
  • How to Get the First Key Name of a JavaScript Object
  • How to Check if a Value is an Object in JavaScript
  • How to Check if a Key Exists in JavaScript Object
  • How to List the Properties of a JavaScript Object
  • How to Convert Arguments Object to an Array
  • How to Check if JavaScript Object is Empty
  • How to Sort JavaScript Object by Key
  • JavaScript Object.keys, Values, Entries
  • JavaScript Proxy and Reflect
  • JavaScript Loops: while and for
  • Javascript Objects
  • JavaScript Array methods
  • JavaScript Symbol Types
  • JavaScript Arrays

Источник

Читайте также:  PHP Function Page
Оцените статью