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?
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?
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.
var item = [{ a: 1 }, { b: 2 }];
Array.prototype.duplicate = function() {
console.log(this.concat(this));
};
item.duplicate();
let item = [
{ a: 1 },
{ b: 2 }
];
item.forEach(obj => {
item.push(obj);
})
console.log(item)
With a loop