Pushing objects to array javascript

5 Ways Add Object To Array Javascript

In this article, we are going to learn how Javascript push object to array in 5 different ways with examples.

JavaScript array can store multiple data types. For example, we can store numbers, strings, booleans, arrays, and objects as well.

An array of objects is generally used to store real-life data. For example, we can store user data, product data, and so on.

Let’s see how we can add object to array in Javascript.

1. Javascript push object to array using push() method

The push() is the most famous array method in JavaScript. It is used to add an element to the end of an array.

This can be used to add any data type to an array. For example, we can add a string, number, boolean, object, array, etc. to an array.

Читайте также:  Php www root directory

The push() method accepts one or more arguments. The arguments are added to the end of the array.

To add an object to array using push() method pass the reference of an object or direct object as an argument to the method.

Add the object to an array using push()

let arr = [1, 2]; let obj = < name: "John", age: 30 >; // push object to array arr.push(obj); console.log(arr);

After running the code, you can see the object is pushed to the end of the array.

You can also directly pass an object to the push() method.

let arr = [1, 2]; // push object to array arr.push(< name: "John", age: 30 >); console.log(arr);

You can also add multiple objects to the array using the push() method. Pass multiple objects to the method by separating them with a comma.

let arr = [1, 2]; let obj1 = < name: "John", age: 30 >; let obj2 = < name: "Peter", age: 40 >; arr.push(obj1, obj2); console.log(arr);

2. Javascript push object to array using unshift() method

The unshift() is another array method that can be used to add any object to the array.

The unshift() method accepts one or more arguments and adds them to the beginning of the array.

You can also add an object to the array by passing reference of the object to the methods or by directly passing the object to the method.

Add the object to an array using unshift()

// add object to array javascript let arr = [1, 2]; let obj = < name: "John", age: 30 >; arr.unshift(obj); console.log(arr);

You can also add multiple objects by passing multiple objects to the method and separating them with a comma.

let arr = [1, 2]; let obj1 = < name: "John", age: 30 >; let obj2 = < name: "Peter", age: 40 >; arr.unshift(obj1, obj2); console.log(arr);

3. Javascript push object to array using splice() method

The splice() is a very powerful method. It can add or remove any element at any position in an array.

It accepts three arguments.

  1. Index — The position where the element is to be added or removed.
  2. How many elements are to be removed — The number of elements to be removed from the array.
  3. What to be added — The element to be added to the array.

To add an element number of elements to remove would be 0.

let arr = [1, 2, 3]; let obj = < name: "John", age: 30 >; // add object to array at index 2 arr.splice(2, 0, obj); console.log(arr);

The splice() method can also accept multiple arguments. After 2nd argument, any number of arguments passed to the method is added to the array.

let arr = [1, 2, 3]; let obj1 = < name: "John", age: 30 >; let obj2 = < name: "Peter", age: 40 >; // add 2 objects to array at index 2 arr.splice(2, 0, obj1, obj2); console.log(arr);

4. Add object by assigning to array

A new element can be added to an array by assigning the element to the array at a particular index.

For example, arr[0] = «John»; will add «John» to the first index of the array.

Similarly, you can assign an object to an array using this method.

let arr = [1, 2, 3]; let obj = < name: "John", age: 30 >; arr[0] = obj; console.log(arr);

5. Javascript push object to array using spread operator

In general, the spread operator is used to expand the elements of an array into a list of arguments. But we can use it to add elements to the array.

Spread the array in a square bracket and add the object as the next argument.

let arr = [1, 2, 3]; let obj = < name: "John", age: 30 >; arr = [. arr, obj]; console.log(arr);

Conclusion

add object to array javascript

In this short guide, we looked at 5 ways to add object to array javascript.

The 5 methods are push(), unshift(), splice(), assign method and spread operator.

Источник

Array.prototype.push()

The push() method adds the specified elements to the end of an array and returns the new length of the array.

Try it

Syntax

push() push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) 

Parameters

The element(s) to add to the end of the array.

Return value

The new length property of the object upon which the method was called.

Description

The push() method appends values to an array.

Array.prototype.unshift() has similar behavior to push() , but applied to the start of an array.

The push() method is a mutating method. It changes the length and the content of this . In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* . ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat() .

The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples

Adding elements to an array

The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

const sports = ["soccer", "baseball"]; const total = sports.push("football", "swimming"); console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] console.log(total); // 4 

Merging two arrays

This example uses spread syntax to push all elements from a second array into the first one.

const vegetables = ["parsnip", "potato"]; const moreVegs = ["celery", "beetroot"]; // Merge the second array into the first one vegetables.push(. moreVegs); console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot'] 

Merging two arrays can also be done with the concat() method.

Calling push() on non-array objects

The push() method reads the length property of this . It then sets each index of this starting at length with the arguments passed to push() . Finally, it sets the length to the previous length plus the number of pushed elements.

const arrayLike =  length: 3, unrelated: "foo", 2: 4, >; Array.prototype.push.call(arrayLike, 1, 2); console.log(arrayLike); // const plainObj = >; // There's no length property, so the length is 0 Array.prototype.push.call(plainObj, 1, 2); console.log(plainObj); // 

Using an object in an array-like fashion

As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.

Note that we don’t create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.

const obj =  length: 0, addElem(elem)  // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem); >, >; // Let's add some empty objects just to illustrate. obj.addElem(>); obj.addElem(>); console.log(obj.length); // 2 

Note that although obj is not an array, the method push successfully incremented obj ‘s length property just like if we were dealing with an actual array.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 17, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to Push an Object to an Array in JavaScript

To push an object to an array in JavaScript, call the push() method on the array with the object as an argument, i.e., arr.push(obj) . The push() method will add the element to the end of the array.

const arr = []; const obj = < name: 'Jeff' >; // 👇 Push object to array arr.push(obj); // [ < name: 'Jeff' >] console.log(arr); 

The push() method takes an object and adds it to the end of an array.

Push object to array during initialization

If the variable is newly created just before the object is pushed (like in the previous example), you can simply place the object in between the square brackets ( [] ) to include it in the array as the variable is initialized:

const obj = < name: 'Jeff' >; // 👇 Push object to array with initialization const arr = [obj]; console.log(arr); 

Push multiple objects to array

The push() method actually accepts a variable number of arguments. They are each added to the end of the array, in the order in which they are passed to push() .

const arr = []; const obj1 = < name: 'Samantha' >; const obj2 = < name: 'Chris' >; const obj3 = < name: 'Mike' >; arr.push(obj1, obj2, obj3); // [ < name: 'Samantha' >, < name: 'Chris' >, < name: 'Mike' >] console.log(arr); 

Push object to array without mutation

The push() method adds an object to the array in place, which means it gets modified. If you don’t want this, you can use the spread syntax ( . ) to create a copy of the original array, before calling push() :

const arr = [< name: 'Jerry' >]; const newArr = [. arr]; newArr.push(< name: 'Mia' >); // [ < name: 'Jerry' >, < name: 'Mia' >] console.log(newArr); // 👇 Original not modified console.log(arr); // [ < name: 'Jerry' >] 

Similar to what we did earlier, we can include the object in the square brackets, after the spread syntax, to push the object to the array’s copy as it is initialized:

const arr = [< name: 'Jerry' >]; // 👇 Push object to array without mutation const newArr = [. arr, < name: 'Mia' >]; // [ < name: 'Jerry' >, < name: 'Mia' >] console.log(newArr); // Original not modified console.log(arr); // [ < name: 'Jerry' >] 

While not always necessary, by avoiding mutations we can make our code more readable, predictable, and modular.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Источник

Оцените статью