×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

How to concatenate array-like objects in JavaScript?

By IncludeHelp Last updated : January 20, 2024

Problem statement

Given two array-like JavaScript objects, you have to concatenate them.

Concatenating array-like objects

Since the Array.concat() method does not treat all array-like objects as an array. To concatenate array-like objects, you can use the Symbol.isConcatSpreadable attribute with its value as true. [source]

JavaScript code to concatenate array-like objects

The following example concatenates two array-like objects object1 and object2.

// creating two array-like objects
const object1 = {
  id: 101,
  age: 21,
  marks: 450
};
const object2 = {
  0: 40,
  1: 50,
  2: 60,
  length: 3,
  [Symbol.isConcatSpreadable]: true
};

// concatenating 
const result = [0].concat(object1, object2);

console.log(result);

Output

The output of the above code is:

[0, {id: 101, age: 21, marks: 450}, 40, 50, 60]

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.