- JavaScript Objects
- JavaScript Objects
- Object Definition
- Example
- Example
- Object Properties
- Accessing Object Properties
- Example1
- Example2
- Object Methods
- Example
- What is this?
- Note
- See Also:
- The this Keyword
- Accessing Object Methods
- Example
- Example
- Do Not Declare Strings, Numbers, and Booleans as Objects!
- JavaScript Object Properties
- JavaScript Properties
- Accessing JavaScript Properties
- Example 1
- Example 2
- JavaScript for. in Loop
- Syntax
- Example
- Adding New Properties
- Example
- Deleting Properties
- Example
- Example
- Nested Objects
- Example
- Example
- Example
- Example
- Example
- Nested Arrays and Objects
- Example
- Example
- » + myObj.cars[i].name + «
- Property Attributes
- Prototype Properties
- JavaScript Object Get Value By Key
- Javascript object keys
- 1. Using dot notation
- 2. Using square bracket
- Javascript object get value by key variable
- JS object get value by key string
- javascript Get Object Value by Key in Array
- JavaScript access nested object property with variable
- Conclusion
JavaScript Objects
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a colon).
It is a common practice to declare objects with the const keyword.
Learn more about using const with objects in the chapter: JS Const.
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
Object Properties
The name:values pairs in JavaScript objects are called properties:
Property | Property Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
Accessing Object Properties
You can access object properties in two ways:
Example1
Example2
JavaScript objects are containers for named values called properties.
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Property | Property Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() |
A method is a function stored as a property.
Example
const person = <
firstName: «John»,
lastName : «Doe»,
id : 5566,
fullName : function() <
return this.firstName + » » + this.lastName;
>
>;
In the example above, this refers to the person object.
I.E. this.firstName means the firstName property of this.
I.E. this.firstName means the firstName property of person.
What is this?
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. |
Alone, this refers to the global object. |
In a function, this refers to the global object. |
In a function, in strict mode, this is undefined . |
In an event, this refers to the element that received the event. |
Methods like call() , apply() , and bind() can refer this to any object. |
Note
See Also:
The this Keyword
In a function definition, this refers to the «owner» of the function.
In the example above, this is the person object that «owns» the fullName function.
In other words, this.firstName means the firstName property of this object.
Accessing Object Methods
You access an object method with the following syntax:
Example
If you access a method without the () parentheses, it will return the function definition:
Example
Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword » new «, the variable is created as an object:
x = new String(); // Declares x as a String object
y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object
Avoid String , Number , and Boolean objects. They complicate your code and slow down execution speed.
You will learn more about objects later in this tutorial.
JavaScript Object Properties
Properties are the most important part of any JavaScript object.
JavaScript Properties
Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.
Accessing JavaScript Properties
The syntax for accessing the property of an object is:
The expression must evaluate to a property name.
Example 1
Example 2
JavaScript for. in Loop
The JavaScript for. in statement loops through the properties of an object.
Syntax
The block of code inside of the for. in loop will be executed once for each property.
Looping through the properties of an object:
Example
const person = <
fname:» John»,
lname:» Doe»,
age: 25
>;
for (let x in person) txt += person[x];
>
Adding New Properties
You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists — you can then give it new properties:
Example
Deleting Properties
The delete keyword deletes a property from an object:
Example
const person = <
firstName: «John»,
lastName: «Doe»,
age: 50,
eyeColor: «blue»
>;
Example
const person = <
firstName: «John»,
lastName: «Doe»,
age: 50,
eyeColor: «blue»
>;
The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect on variables or functions.
The delete operator should not be used on predefined JavaScript object properties. It can crash your application.
Nested Objects
Values in an object can be another object:
Example
You can access nested objects using the dot notation or the bracket notation:
Example
Example
Example
Example
Nested Arrays and Objects
Values in objects can be arrays, and values in arrays can be objects:
Example
To access arrays inside arrays, use a for-in loop for each array:
Example
for (let i in myObj.cars) <
x += «
» + myObj.cars[i].name + «
«;
for (let j in myObj.cars[i].models) <
x += myObj.cars[i].models[j];
>
>
Property Attributes
All properties have a name. In addition they also have a value.
The value is one of the property’s attributes.
Other attributes are: enumerable, configurable, and writable.
These attributes define how the property can be accessed (is it readable?, is it writable?)
In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
Prototype Properties
JavaScript objects inherit the properties of their prototype.
The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.
JavaScript Object Get Value By Key
You as a JavaScript developer are always looking for a way to get the value of a key from an object. This is a very common task in JavaScript.
In this tutorial, you will learn how to extract the value of the key from the object in JavaScript.
- Using dot notation
- Using Square bracket
Javascript object keys
The key of an object is the name of the property.
You can think of the key as the named index of an associative array. JavaScript does not have an associative array. Instead, JavaScript objects are used to store key-value pairs.
In general, the key of the object is known, and using the key you can access the value of the object.
There are 2 ways to access the value of the object.
- Using dot notation
- Using square bracket
1. Using dot notation
The dot notation is the most commonly used way to access the value of the object.
To use this write the name of the object followed by a dot and then the name of the key. Example person.name (where the person is an object and name is the key).
var person = < name: "John", age: 30, city: "New York" >; // access value of object // using dot notation console.log(person.name); // John console.log(person.age); // 30 console.log(person.city); // New York
The above code will print the value of the key name in the console.
2. Using square bracket
The square bracket is another way to access the value of the object.
To use this write the name of the object followed by a square bracket and then the name of the key. Example person[«name»] (where the person is an object and name is the key).
var person = < name: "John", age: 30, city: "New York" >; // access value of object // using square bracket console.log(person["name"]); // John console.log(person["age"]); // 30 console.log(person["city"]); // New York
Javascript object get value by key variable
Sometimes you have the key of an object stored in a variable and you want to access the value of the key. This is a very common scenario.
When you try to access the value now using the variable it gives you undefined.
Here is an example to show this.
const person = < name: "John", age: 30, city: "New York" >; // key stored in a variable var userName = "name"; // trying to access value using dot notation console.log(person.userName); // undefined
The above code will print undefined in the console because Javascript treats ‘userName’ as a key and not a variable. Since the variable is not a key of the object, it will give you undefined.
So to access the value of the object when you have the key stored in a variable use the square bracket notation.
const person = < name: "John", age: 30, city: "New York" >; // key stored in a variable var userName = "name"; // using square bracket console.log(person[userName]); // John
Note : Always use the square bracket notation when you have the key stored in a variable.
Here is another example where the key is passed in a Javascript function and you have to use an argument to access the value.
const person = < name: "John", age: 30, city: "New York" >; // using square bracket to access value // stored in a variable (argument) function getValue(key) < return personJavascript get object vars; >console.log(getValue("name")); // John
JS object get value by key string
Similar to the previous example, when you just have the key as a string, you can access the value of the key.
The same as the previous example, you can’t use dot notation to access the value of the key. You have to use square bracket notation .
const person = < name: "John", age: 30, city: "New York" >; // key as a string // using square bracket console.log(person["name"]); // John console.log(person["age"]); // 30 console.log(person["city"]); // New York
javascript Get Object Value by Key in Array
As we know, the Object.keys() return an array of all the keys of the object.
So you have an array of keys and you want to access the value of the key. This is the same scenario as iterating object keys in an array.
const person = < name: "John", age: 30, city: "New York" >; // get all keys of the object const keys = Object.keys(person); // getting value of the keys in array for (let i = 0; i
In the above example, we are iterating over the keys of the object and storing keys in an array. Then we are accessing the value of the key using square bracket notation.
JavaScript access nested object property with variable
When you have a nested object, then start chaining the keys either using dot or square bracket notation. But since you have the key stored in a variable, you have to use the square bracket notation.
Let your object be like this:
const person = < name: "John", age: 30, hobbies: < music: "guitar", sport: "football" >, education: < highSchool: "St. John's High School", marks: [< maths: "A+" >, < science: "B+" >] >, city: "New York" >
Now you want to access the marks of the first subject. Simply start the chain with the square bracket notation. Example person[«education»][«marks»][0][«maths»] will give you A+ .
Here is an example to show this.
const person = < name: "John", age: 30, hobbies: < music: "guitar", sport: "football" >, education: < highSchool: "St. John's High School", marks: [< maths: "A+" >, < science: "B+" >] >, city: "New York" > let edu = "education", mrk = "marks", m = "maths"; // accessing marks of first subject console.log(person[edu][mrk][0][m]); // A+
Conclusion
In this short article, we understand how Javascript object get value by key. You can use dot notation or square bracket notation to access the value of the key. But if you have the key stored in a variable, you have to use the square bracket notation.
For nested objects, properties start the chain and use any of the two notation if it fits the discussed concept.