JavaScript objects are containers for named values.
An object has a list of values written as key:value
pairs, with the keys and the values separated by colons.
We use curly braces {} to create an object:
const car = {
color: 'blue';
brand: 'Honda';
};
Note: Spaces and line breaks are not important. An object definition can span multiple lines.
You can access, add or edit a property within an object using dot notation or bracket notation.
We must use bracket notation when accessing keys with numbers, spaces, or special characters.
objectName.propertyName;
// or
objectName["propertyName"];
Example
const person = {
name: "Anna",
age: 22,
hobbies: ["movies", "travel", "art"],
address: {
street: "12 Anderson",
city: "Copenhagen",
country: "Denmark",
},
};
console.log(person.name); // Anna
console.log(person.hobbies[2]); // art
console.log(person.address.country); // Denmark
Destructuring
We can also use destructuring to access the values in the array.
const {name, address: {country}} = person;
console.log(name); // Anna
console.log(country); // Denmark
We can add more properties to an object easily with dot notation.
Example
person.email = "anna@gmail.com"
console.log(person)
// {name: "Anna", age: 22, hobbies: Array(3), address: {…}, email: "anna@gmail.com"}
We can also have a function in an object. For example:
const person = {
firstName: "Anna",
lastName: "Smith",
hobbies: ["movies", "travel", "art"],
getFullName: function () {
return `Full name is ${this.firstName} ${this.lastName}`;
},
};
console.log(person.getFullName()); // Full name is Anna Smith
What is an array of objects?
As its name suggests, an array of objects stores OBJECTS. Each value in the array is an object.
const food = [
{
id: 1,
name: "Chicken curry",
origin: "India"
},
{
id: 2,
name: "Pho",
origin: "Vietnam"
},
{
id: 3,
name: "Kimbap",
origin: "Korea"
}
];
console.log(food[1].name); // Pho
Convert into JSON
JSON is a data format for storing and exchanging data. For example, when we send data to a server, we send it in JSON format and receive it in JSON format.
To convert the array of objects into JSON, we use JSON.stringify()
method.
const foodJSON = JSON.stringify(food);
console.log(foodJSON);
// [{"id":1,"name":"Chicken curry","origin":"India"},{"id":2,"name":"Pho","origin":"Vietnam"},{"id":3,"name":"Kimbap","origin":"Korea"}]
Javascript objects are written as “key: value” pairs.
We can use the Object.values() method to return all values in an array.
const object1 = {
a: "hello",
b: "hi",
c: 24,
};
console.log(Object.values(object1));
// ["hello", "hi", 24]
Similarly, we use the Object.keys() method to return all the keys.
const object1 = {
a: "hello",
b: "hi",
c: 24,
};
console.log(Object.keys(object1));
// ["a", "b", "c"]
To create an object, we can use constructor function or classes.