Modelo

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

5 Ways to Push Values into Objects in JavaScript

Oct 16, 2024

When working with JavaScript objects, you may often need to add or push new values into the object. Fortunately, JavaScript provides several ways to achieve this. In this article, we will explore 5 different methods to push values into objects in JavaScript.

1. Using Dot Notation:

One of the simplest ways to push a new value into an object is by using dot notation. For example:

```

let person = {};

person.name = 'John';

person.age = 30;

```

2. Using Object.assign():

The Object.assign() method can be used to copy all enumerable own properties of one or more source objects to a target object. This can be used to push new key-value pairs into an object. Here's an example:

```

let obj1 = { a: 1, b: 2 };

let obj2 = { c: 3 };

Object.assign(obj1, obj2);

```

3. Using Spread Operator:

The spread operator (...) can be used to push key-value pairs from one object into another. For example:

```

let obj1 = { a: 1, b: 2 };

let obj2 = { ...obj1, c: 3 };

```

4. Using Object.defineProperty():

The Object.defineProperty() method can be used to add a new property to an object, or modify an existing one. Here's an example:

```

let obj = {};

Object.defineProperty(obj, 'name', {

value: 'John',

writable: true,

enumerable: true,

configurable: true

});

```

5. Using Object.setPrototypeOf():

The Object.setPrototypeOf() method can be used to set the prototype of a specified object. This can be useful for pushing new values into objects with prototype inheritance. For example:

```

let obj1 = { a: 1 };

let obj2 = Object.setPrototypeOf(obj1, { b: 2 });

```

These are 5 different ways to push values into objects in JavaScript. Depending on the specific use case and requirements, you can choose the method that best suits your needs. Happy coding!

Recommend