Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Set Values to an Object in JavaScript

Oct 06, 2024

Setting values to an object in JavaScript is a common task in web development. Objects in JavaScript are collections of key-value pairs, where each key is a string (or a Symbol) and each value can be any data type, including other objects. There are several ways to set values to an object in JavaScript. Let's explore some of the most common methods.

1. Dot notation:

You can set values to an object using the dot notation. For example:

const person = {};

person.name = 'John';

person.age = 30;

In this example, we are creating a new object called person and setting its name and age properties using the dot notation.

2. Bracket notation:

Another common way to set values to an object is using the bracket notation. For example:

const person = {};

person['name'] = 'John';

person['age'] = 30;

In this example, we are achieving the same result as the previous example, but using the bracket notation instead.

3. Object.defineProperty():

You can also use the Object.defineProperty() method to set values to an object with more control over the property attributes. For example:

const person = {};

Object.defineProperty(person, 'name', {

value: 'John',

writable: true,

enumerable: true,

configurable: true

});

In this example, we are setting the name property of the person object using the Object.defineProperty() method and defining its value, writability, enumerability, and configurability.

4. Object.assign():

The Object.assign() method can be used to copy the values of all enumerable own properties from one or more source objects to a target object. For example:

const target = {};

const source = { name: 'John', age: 30 };

Object.assign(target, source);

console.log(target); // { name: 'John', age: 30 }

In this example, we are setting the values of the source object to the target object using the Object.assign() method.

These are just a few of the many ways to set values to an object in JavaScript. Depending on your specific use case, you may choose one method over the others. Understanding how to set values to objects is fundamental to mastering JavaScript and building complex applications.

Recommend