nodejs add new property array object

To add a new property to an array object in Node.js, you can follow these steps:

  1. Access the array object: First, you need to access the array object to which you want to add a new property. You can do this by referencing the array object using its variable name or by accessing it through an array index.

  2. Add a new property: Once you have accessed the array object, you can add a new property to it using the dot notation or square bracket notation. The dot notation involves directly specifying the property name after the array object variable name, while the square bracket notation involves using square brackets and specifying the property name as a string.

  3. Assign a value to the new property: After adding the new property, you can assign a value to it by using the assignment operator (=) followed by the desired value. The value can be of any valid data type, such as a string, number, boolean, or even another object.

Here is an example code snippet that demonstrates these steps:

// Step 1: Access the array object
let myArray = [
  { name: "John", age: 25 },
  { name: "Jane", age: 30 },
];

// Step 2: Add a new property
myArray[0].city = "New York";

// Step 3: Assign a value to the new property
myArray[1]["city"] = "London";

console.log(myArray);

In this example, we first access the myArray object, which contains two objects with properties name and age. Then, we add a new property called city to the first object using the dot notation (myArray[0].city). Finally, we assign the value "New York" to the city property of the second object using the square bracket notation (myArray[1]["city"]).

The output of the console.log statement will be:

[
  { name: "John", age: 25, city: "New York" },
  { name: "Jane", age: 30, city: "London" }
]

This shows that the new property city with its corresponding values has been successfully added to the respective objects within the array.