anand patil
anand patil

Reputation: 497

How to clone an item of objects in array?

I have an array as given below -

var x = [{
    name: "Mr.X", 
    age: 22
},{
    name: "Mr.Y", 
    age: 26
},{
    name: "Mr.Z", 
    age: 24
},];

I want to duplicate the 2nd item and put it as the first element. Just to avoid any confusion, I want the resultant array to be as given below -

var x = [{
    name: "Mr.YD", 
    age: 19
},{
    name: "Mr.X", 
    age: 22
},{
    name: "Mr.Y", 
    age: 26
},{
    name: "Mr.Z", 
    age: 24
},];

What I have tried and got - I extracted the 2nd item, and changed the name and age properties. But it is also changing the 2nd item. I know it is because we are changing the reference. But i have no idea how to extract/duplicate item and change only its value.

Upvotes: 0

Views: 64

Answers (2)

Fraz Ghumman
Fraz Ghumman

Reputation: 49

var x = [{
    name: "Mr.X", 
    age: 22
},{
    name: "Mr.Y", 
    age: 26
},{
    name: "Mr.Z", 
    age: 24
},];
console.log(x);
var y = JSON.parse(JSON.stringify(x));
y.unshift({
    name: "Mr.XD", 
    age: 19
});
console.log(y);
  1. Unshift appends on top of array
  2. Push appends on the end of array

Upvotes: 1

Bijeshp009
Bijeshp009

Reputation: 248

if you are looking for clone of the object there are multiple ways

jQuery Extend:

// Shallow copy
  var newObject = jQuery.extend({}, oldObject);

  // Deep copy
  var newObject = jQuery.extend(true, {}, oldObject);

JSON Stringify

var newObject =  JSON.parse(JSON.stringify(oldObject))

Or : Write a clone method by iterating through object props recursively

Then append to the array using the standard array APIs

Upvotes: 1

Related Questions