node js add new object to object array json
// Sample array of objects
const objectArray = [
{ id: 1, name: 'Object 1' },
{ id: 2, name: 'Object 2' },
];
// New object to be added
const newObject = { id: 3, name: 'Object 3' };
// Adding the new object to the array
objectArray.push(newObject);
// Resulting object array after addition
console.log(objectArray);
This code demonstrates adding a new object to an array of objects in Node.js. Here are the steps:
- Declare a sample array of objects called
objectArray
. - Define a new object called
newObject
that you want to add to the array. - Use the
push
method to add thenewObject
to theobjectArray
. - Print the updated
objectArray
to the console to verify the addition.