-3

I got this array of objects

let item = [
  { a: 1 },
  { b: 2 }
]

and would like to duplicate array's elements to the same array. Output should be:

[
  { a: 1 },
  { b: 2 },
  { a: 1 },
  { b: 2 }
] 

Can you help?

CodeJoe
  • 262
  • 2
  • 10
  • The posted question does not appear to include any attempt at all to solve the problem. Stack Overflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Nov 26 '19 at 12:18
  • concat or spread? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – doctorlove Nov 26 '19 at 12:21
  • @doctorlove thanks, concat just do the thing `item = item.concat(item);` – CodeJoe Nov 26 '19 at 12:28

3 Answers3

3

If the first object is the same object as the 3rd object in the array, you can just concat() the array to itself.

let item = [
  { a: 1 },
  { b: 2 }
];
let output = item.concat( item );
console.log( JSON.stringify( output ));
console.log( 'Items are the same: ', output[ 0 ] === output[ 2 ] );

If the objects have to be different objects with the same properties and values, you'll need to clone all of those objects.

let item = [
  { a: 1 },
  { b: 2 }
];
let clone = collection => collection.map( item => Object.assign( {}, item ));
let output = [ ...clone( item ), ...clone( item ) ];
console.log( JSON.stringify( output ));
console.log( 'Items are the same: ', output[0 ] === output[ 2 ] );

See the differences between pass-by-value and pass-by-reference for more information and why this matters.

Shilly
  • 8,511
  • 1
  • 18
  • 24
0
var item = [{ a: 1 }, { b: 2 }];

Array.prototype.duplicate = function() {
  console.log(this.concat(this));
};

item.duplicate();
Naveen Kashyap
  • 372
  • 1
  • 9
0

let item = [
  { a: 1 },
  { b: 2 }
];

item.forEach(obj => {
  item.push(obj);
})

console.log(item)

With a loop

Kevin.a
  • 4,094
  • 8
  • 46
  • 82