How to use array concatenation (concat) In Typescript
In this approach we are using the concat method which is used to merge two or more arrays. It does not mutate the original arrays but returns a new array containing the elements of the original arrays.
Syntax:
let newArray = array.concat(newObj);
Example: In this example we initializes an array of products, appends a new product object to it using concat(), and logs the updated array with the new product included.
let products: { name: string, price: number, category: string }[] =
[
{
name: 'Laptop',
price: 1000,
category: 'Electronics'
},
{
name: 'Headphones',
price: 100,
category: 'Electronics'
}
];
let newProduct = {
name: 'Smartphone',
price: 800,
category: 'Electronics'
};
let newProducts = products.concat(newProduct);
console.log(newProducts);
Output:
[{
"name": "Laptop",
"price": 1000,
"category": "Electronics"
}, {
"name": "Headphones",
"price": 100,
"category": "Electronics"
}, {
"name": "Smartphone",
"price": 800,
"category": "Electronics"
}]
Add an Object to an Array in TypeScript
TypeScript allows adding an object to an array that is a common operation when working with collections of data.
Below are the approaches to add an object to an array in TypeScript:
Table of Content
- Using the push method
- Using the Spread Operator (…)
- Using array concatenation (concat)
- Using Array Unshift
- Using Index Assignment:
- Using Array splice() Method