객체 속성 변경 방법

JavaScript is a highly flexible programming language that allows you to manipulate objects and their properties. There are a few different ways to change the properties of an object in JavaScript, and in this blog post, we’ll explore some of these methods.

1. Dot notation

One common way to change a property of an object is to use the dot notation. This method allows you to directly access and modify the property of an object.

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

person.name = "Jane";
person.age = 25;

console.log(person);
// Output: { name: "Jane", age: 25 }

In the above example, we have an object person with properties name and age. We use the dot notation to change the values of these properties to "Jane" and 25, respectively.

2. Bracket notation

Another way to change a property of an object is to use the bracket notation. This method allows you to access and modify the property of an object using a variable or an expression.

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

person[propertyName] = "Jane";

console.log(person);
// Output: { name: "Jane", age: 30 }

In the above example, we define a variable propertyName with a value of "name". We then use the bracket notation to change the value of person[propertyName] to "Jane".

3. Object.assign()

The Object.assign() method can also be used to change properties of an object. This method allows you to merge the properties of multiple objects into a target object.

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

const newProperties = {
  name: "Jane",
  city: "New York"
};

Object.assign(person, newProperties);

console.log(person);
// Output: { name: "Jane", age: 30, city: "New York" }

In the above example, we have an object person with properties name and age. We define another object newProperties with properties name and city. We then use Object.assign() to merge the properties of newProperties into person, effectively changing the name property to "Jane" and adding a new city property.

These are just a few of the many ways to change the properties of an object in JavaScript. The chosen method may vary depending on the specific use case and requirements of your code. Experiment with different approaches to find the one that best suits your needs.