Update array with new object JavaScript without using index
- Published
- Reading time
- 2 min read
- Length
- 368 words
On this page
Update array with new object JavaScript without using index#
As a web developer, I have come across situations where I need to update an array with a new object in JavaScript without using the index. In such cases, I found two ways to achieve this.
Using Spread Operator#
The first way to update an array with a new object in JavaScript without using the index is by using the spread operator. The spread operator allows us to spread the existing array into a new array and add the new object at the end of it.
const array = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}];
const newObj = {id: 3, name: 'Jack'};
const newArray = [...array, newObj];
console.log(newArray); // [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 3, name: 'Jack'}]In the above example, we have an existing array of objects called 'array'. We want to add a new object called 'newObj' to this array without using the index. We use the spread operator to spread the 'array' into a new array called 'newArray' and add the 'newObj' at the end of it. The output will be the updated array with the new object.
Using Concat Method#
The second way to update an array with a new object in JavaScript without using the index is by using the concat method. The concat method allows us to concatenate two arrays into a new array.
const array = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}];
const newObj = {id: 3, name: 'Jack'};
const newArray = array.concat(newObj);
console.log(newArray); // [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 3, name: 'Jack'}]In the above example, we have an existing array of objects called 'array'. We want to add a new object called 'newObj' to this array without using the index. We use the concat method to concatenate the 'array' and 'newObj' into a new array called 'newArray'. The output will be the updated array with the new object.
These are the two ways I found to update an array with a new object in JavaScript without using the index. Both methods are equally efficient and easy to use. It depends on the developer's preference which method they want to use.