0

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.

8
  • Is there a specific reason you need to clone an existing object in the array instead of just creating a new one? Commented Nov 30, 2015 at 11:23
  • 1
    Refer this: jsfiddle.net/e7kLb9f8 Commented Nov 30, 2015 at 11:24
  • I didn't follow your question. But the resultant array could be "y" instead of "x". Commented Nov 30, 2015 at 11:24
  • @RayonDabre - Only one thing - the result should also be an array of objects, just like the input. Commented Nov 30, 2015 at 11:31
  • JSON.stringify is being used just to demonstrate the result..You can remove it! Commented Nov 30, 2015 at 11:32

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
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

1 Comment

while it usually works, I would never recommend using JSON just to clone an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.