Javascript finding 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.

Источник

3 Ways To Access Object Properties in JavaScript

3 Ways To Access Object Properties in JavaScript

You can access the properties of an object in JavaScript in 3 ways:

  1. Dot property accessor: object.property
  2. Square brackets property access: object[‘property’]
  3. Object destructuring: const < property >= object

Let’s see how each syntax to access the properties work. And understand when it’s reasonable, depending on the situation, to use one way or another.

1. Dot property accessor

A common way to access the property of an object is the dot property accessor syntax:

expression should evaluate to an object, and identifier is the name of the property you’d like to access.

For example, let’s access the property name of the object hero :

const hero = < name: 'Batman' >; // Dot property accessor hero.name; // => 'Batman'

hero.name is a dot property accessor that reads the property name of the object hero .

You can use the dot property accessor in a chain to access deeper properties: object.prop1.prop2 .

Choose the dot property accessor when the property name is known ahead of time.

1.1 Dot property accessor requires identifiers

The dot property accessor works correctly when the property name is a valid identifier. An identifier in JavaScript contains Unicode letters, $ , _ , and digits 0..9 , but cannot start with a digit.

This is not a problem, because usually, the property names are valid identifiers: e.g. name , address , street , createdBy .

But sometimes properties are not valid identifiers:

const weirdObject = < 'prop-3': 'three', '3': 'three' >; weirdObject.prop-3; // => NaN weirdObject.3; // throws SyntaxError: Unexpected number

Because prop-3 and 3 are invalid identifiers, the dot property accessor doesn’t work:

  • weirdObject.prop-3 evaluates to NaN , instead of the expected ‘tree’
  • weirdObject.3 throws a SyntaxError !

Why does the expression weirdObject.prop-3 evaluate to NaN ? Please write your answer in a comment below!

To access the properties with these special names, use the square brackets property accessor (which is described in the next section):

const weirdObject = < 'prop-3': 'three', '3': 'three' >; weirdObject['prop-3']; // => 'three' weirdObject[3]; // => 'three'

The square brackets syntax accesses without problems the properties that have special names: weirdObject[‘prop-3’] and weirdObject[3] .

2. Square brackets property accessor

The square brackets property accessor has the following syntax:

The first expression should evaluate to an object and the second expression should evaluate to a string denoting the property name.

const property = 'name'; const hero = < name: 'Batman' >; // Square brackets property accessor: hero['name']; // => 'Batman' hero[property]; // => 'Batman'

hero[‘name’] and hero[property] both read the property name by using the square brackets syntax.

Choose the square brackets property accessor when the property name is dynamic, i.e. determined at runtime.

3. Object destructuring

The basic object destructuring syntax is pretty simple:

identifier is the name of the property to access and expression should evaluate to an object. After the destructuring, the variable identifier contains the property value.

const hero = < name: 'Batman' >; // Object destructuring: const < name >= hero; name; // => 'Batman'

const < name >= hero is an object destructuring. The destructuring defines a variable name with the value of property name .

When you get used to object destructuring, you will find that its syntax is a great way to extract the properties into variables.

Choose the object destructuring when you’d like to create a variable having the property value.

Note that you can extract as many properties as you’d like:

3.1 Alias variable

If you’d like to access the property, but create a variable name different than the property name, you could use aliasing.

identifier is the name of the property to access, aliasIdentifier is the variable name, and expression should evaluate to an object. After the destructuring, the variable aliasIdentifier contains the property value.

const hero = < name: 'Batman' >; // Object destructuring: const < name: heroName >= hero; heroName; // => 'Batman'

const < name: heroName >= hero is an object destructuring. The destucturing defines a new variable heroName (instead of name as in previous example), and assigns to heroName the value hero.name .

3.2 Dynamic property name

What makes the object destructuring even more useful is that you could extract to variables properties with the dynamic value:

The first expression should evaluate to a property name, and the identifier should indicate the variable name created after the destructuring. The second expression should evaluate to the object you’d like to destructure.

const property = 'name'; const hero = < name: 'Batman' >; // Object destructuring: const < [property]: name >= hero; name; // => 'Batman'

const < [property]: name >= hero is an object destructuring that dynamically, at runtime, determines what property to extract.

4. When the property doesn’t exist

If the accessed property doesn’t exist, all 3 accessor syntaxes evalute to undefined :

const hero = < characterName: 'Batman' >; hero.name; // => undefined hero['name']; // => undefined const < name >= hero; name; // => undefined

The property name doesn’t exist in the object hero . Thus the dot property accessor hero.name , square brackets property accessor hero[‘name’] and the variable name after destructuring evaluate to undefined .

5. Conclusion

JavaScript provides a bunch of good ways to access object properties.

The dot property accessor syntax object.property works nicely when you know the variable ahead of time.

When the property name is dynamic or is not a valid identifier, a better alternative is square brackets property accessor: object[propertyName] .

The object destructuring extracts the property directly into a variable: < property >= object . Moreover, you can extract the dynamic property names (determined at runtime): < [propertName]: variable >= object .

There are no good or bad ways to access properties. Choose depending on your particular situation.

Источник

3 Ways to Check If an Object Has a Property/Key in JavaScript

Post cover

In this post, you’ll read 3 common ways to check for property or key existence in a JavaScript object.

Note: In the post, I describe property existence checking, which is the same as checking for key existence in an object.

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn’t easy. but fortunately with a good teacher you can shortcut.

Take «Modern JavaScript From The Beginning 2.0» course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

Table of Contents

Every JavaScript object has a special method object.hasOwnProperty(‘myProp’) that returns a boolean indicating whether object has a property myProp .

In the following example, hasOwnProperty() determines the presence of properties name and realName :

hero.hasOwnProperty(‘name’) returns true because the property name exists in the object hero .

On the other side, hero doesn’t have realName property. Thus hero.hasOwnProperty(‘realName’) returns false — denoting a missing property.

The method name hasOwnProperty() suggests that it looks for the own properties of the object. The own properties are those defined directly upon the object.

This way hasOwnProperty() doesn’t detect the toString — an inherited method from the prototype object:

‘myProp’ in object also determines whether myProp property exists in object .

Let’s use in operator to detect the existence of name and realName in hero object:

‘name’ in hero evaluates to true because hero has a property name .

On the other side, ‘realName’ in hero evaluates to false because hero doesn’t have a property named ‘realName’ .

in operator has a short syntax, and I prefer it over hasOwnProperty() method.

The main difference between hasOwnProperty() method and in operator is that the latter checks within own and inherited properties of the object.

That’s why, in contrast to hasOwnProperty() , the in operator detects that hero object contains the inherited property toString :

3. Comparing with undefined

Accessing a non-existing property from an object results in undefined :

hero.realName evaluates to undefined because realName property is missing.

Now you can see the idea: you can compare with undefined to determine the existence of the property.

hero.name !== undefined evaluates to true , which shows the existence of property.

On the other side, hero.realName !== undefined is false , which indicates that realName is missing.

Comparing with undefined to detect the existence of property is a cheap and dirty approach.

But be aware of false-negatives. If the property exists, but has undefined value (case, however, rarely happening), comparing against undefined evaluates incorrectly to false :

Even if the property name exists (but has undefined value), hero.name !== undefined evaluates to false : which incorrectly indicates a missing property.

There are mainly 3 ways to check if the properties or keys exist in an object.

The first way is to invoke object.hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise.

hasOwnProperty() searches only within the own properties of the object.

The second approach makes use of propName in object operator. The operator evaluates to true for an existing property, and false otherwise.

in operator looks for properties existence in both own and inherited properties.

Finally, you can simply use object.propName !== undefined and compare against undefined directly.

What’s your preferred way to check for properties existence?

Источник

Читайте также:  Http запрос php пример
Оцените статью