Reputation: 497
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
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);
Upvotes: 1
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