DEV Community

Whoissosick
Whoissosick

Posted on • Edited on

Object [JS]

const exampleObject = {
  propertyName: value;
}
Enter fullscreen mode Exit fullscreen mode

These pieces of information are called properties, and they consist of a name (or key) and a value.

There are two main ways to access object properties in JavaScript: dot notation and bracket notation.

console.log(person.name);  // Alice
console.log(person["name"]); // Alice
console.log(oddObject["1stProperty"]);  // Hello
Enter fullscreen mode Exit fullscreen mode

How Can You Remove Properties from an Object?

delete operator

const person = {
  name: "Alice",
  age: 30,
  job: "Engineer"
};

delete person.job;

console.log(person.job); // undefined
Enter fullscreen mode Exit fullscreen mode

Another way to remove properties is by using destructuring assignment with rest parameters. This approach doesn't actually delete the property, but it creates a new object without the specified properties:

const person = {
  name: "Bob",
  age: 25,
  job: "Designer",
  city: "New York"
};

const { job, city, ...remainingProperties } = person;

// { name: "Bob", age: 25 }
console.log(remainingProperties);
Enter fullscreen mode Exit fullscreen mode

In this example, we use destructuring to extract job and city from the person object, and collect the remaining properties into a new object called remainingProperties. This creates a new object without the job and city properties.

How to Check If an Object Has a Property?

hasOwnProperty() method and in operator returns boolean

const person = {
  name: "Alice",
  age: 30
};

console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("job")); // false

const person = {
  name: "Bob",
  age: 25
};
console.log("name" in person);  // true
Enter fullscreen mode Exit fullscreen mode
const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2020
};

console.log(car.brand !== undefined); // true
console.log(car.color !== undefined); // false
Enter fullscreen mode Exit fullscreen mode

In this code, we check if car.brand and car.color are not undefined. This works because accessing a non-existent property on an object returns undefined. However, this method can give false negatives if a property explicitly has the value undefined.

How Do You Work with Accessing Properties from Nested Objects and Arrays in Objects?

const person = {
  name: "Alice",
  age: 30,
  contact: {
    email: "alice@example.com",
    phone: {
      home: "123-456-7890",
      work: "098-765-4321"
    }
  }
};

console.log(person.contact.phone.work); // "098-765-4321"
console.log(person['contact']['phone']['work']); // "098-765-4321"
Enter fullscreen mode Exit fullscreen mode

Now, let’s take a look at how we can access data where one of the object properties has the value of an array. Here is a modified person object that includes an array of addresses:

const person = {
  name: "Alice",
  age: 30,
  addresses: [
    { type: "home", street: "123 Main St", city: "Anytown" },
    { type: "work", street: "456 Market St", city: "Workville" }
  ]
};

console.log(person.addresses[1].city); // "Workville"
Enter fullscreen mode Exit fullscreen mode

What Is the Difference Between Primitive and Non-Primitive Data Types?

Primitive data types are the simplest form of data in JavaScript. They include numbers, strings, booleans, null, undefined, and symbols. These types are called "primitive" because they represent single values and are not objects.

Primitive values are immutable, which means once they are created, their value cannot be changed. However, you can reassign a new value to the variable. Here's an example of working with primitive data types:

et num1 = 5;
let num2 = num1;
num1 = 10;

console.log(num2); // 5
Enter fullscreen mode Exit fullscreen mode

When you create a variable with a non-primitive value, what's stored in the variable is actually a reference to the location in memory where the object is stored, not the object itself. This leads to some important differences in behavior. Here's an example with non-primitive types:

const originalPerson = { name: "John", age: 30 };
const copiedPerson = originalPerson;

originalPerson.age = 31;

console.log(copiedPerson.age); // 31
Enter fullscreen mode Exit fullscreen mode

This is known as shallow copying by reference.

What Is the Difference Between Functions and Object Methods?

Object methods, on the other hand, are functions that are associated with an object. They are defined as properties of an object and can access and manipulate the object's data.

const person = {
    name: "Bob",
    age: 30,
    sayHello: function() {
        return "Hello, my name is " + this.name;
    }
};

console.log(person.sayHello()); // "Hello, my name is Bob"
Enter fullscreen mode Exit fullscreen mode

A difference between functions and methods is how they are invoked. Functions are called by their name, while methods are called using dot notation on the object they belong to. For example, we call the greet function as greet("Alice"), but we call the sayHello method as person.sayHello().

What Is JSON, and How Do You Access Values Using Bracket and Dot Notation?

JSON stands for JavaScript Object Notation. Since JSON is language-independent, you can easily send JSON data from a Java application to a Python application, or from a JavaScript application to a C# application.

{
  "name": "Alice",
  "age": 30,
  "isStudent": false,
  "list of courses": ["Mathematics", "Physics", "Computer Science"]
}
Enter fullscreen mode Exit fullscreen mode

Each key must be wrapped in double quotes, otherwise you will get an error.

How Do JSON.parse() and JSON.stringify() Work?

const user = {
  name: "John",
  age: 30,
  isAdmin: true
};

const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"John","age":30,"isAdmin":true}'
Enter fullscreen mode Exit fullscreen mode

The JSON.stringify() method also accepts an optional parameter called a replacer, which can be a function or an array. Here is an example of using an array for the optional replacer parameter:

const developerObj = {
  firstName: "Jessica",
  isAwesome: true,
  isMusician: true,
  country: "USA",
};

// result: {"firstName":"Jessica","country":"USA"}
console.log(JSON.stringify(developerObj, ["firstName", "country"]));
Enter fullscreen mode Exit fullscreen mode

Replacer as function

const product = {
    name: "Телефон",
    price: 1000,
    currency: "USD",
    createdAt: new Date('2023-01-15')
};

const productJSON = JSON.stringify(product, function(key, value) {
    // Преобразуем даты в читаемый формат
    if (value instanceof Date) {
        return value.toISOString().split('T')[0]; // "2023-01-15"
    }

    // Исключаем поле currency
    if (key === 'currency') {
        return undefined; // исключаем из результата
    }

    return value; // все остальное оставляем как есть
});

console.log(productJSON);
// {"name":"Телефон","price":1000,"createdAt":"2023-01-15"}
Enter fullscreen mode Exit fullscreen mode

Another optional parameter for the JSON.stringify() method would be the spacer parameter. This allows you to control the spacing for the stringified result:

const developerObj = {
  firstName: "Jessica",
  isAwesome: true,
  isMusician: true,
  country: "USA",
};

console.log(JSON.stringify(developerObj, null, 2));

/* result
{
  "firstName": "Jessica",
  "isAwesome": true,
  "isMusician": true,
  "country": "USA"
}
*/
Enter fullscreen mode Exit fullscreen mode

What Is the Optional Chaining Operator, and How Does It Work?

The optional chaining operator is most useful when you're not sure if a property or method exists. It helps prevent errors and makes your code more robust.

const user = {
  name: "John",
  profile: {
    email: "john@example.com",
    address: {
      street: "123 Main St",
      city: "Somewhere"
    }
  }
};

console.log(user.profile?.address?.street); // "123 Main St"
console.log(user.profile?.phone?.number);   // undefined
Enter fullscreen mode Exit fullscreen mode

Top comments (0)