Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Cloning an object in JavaScript

The below first logs 0, and then logs 1. How do I store a copy of the object, rather than a reference to it?

debug.log(vi.details.segment);
vi.nextSegment = vi.details;
vi.nextSegment.segment++;
debug.log(vi.details.segment);
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

To clone an object in jQuery:

var vi.nextSegment = jQuery.extend({}, vi.details);

NOTE: The above is a shallow copy: any nested objects or arrays will be copied by reference - meaning any changes you make to vi.nextSegment.obj[prop] will be reflected in vi.details.obj[prop]. If you want a completely new object which is completely separate from the original, you will need to do a deep copy (pass true as the first parameter):

var vi.nextSegment = jQuery.extend(true, {}, vi.details);

To read up more on extend, see here.

over 4 years ago · Santiago Trujillo Report

0

Take a look at the post: What is the most efficient way to clone a javascript object

As per John Resig's answer:

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

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

More information can be found in the jQuery documentation.

over 4 years ago · Santiago Trujillo Report

0

This worked better for me cloning an object using jQuery "parseJSON()" and "JSON.stringify()"

$.ajax({
  url: 'ajax/test.html',
  dataType: 'json',
  success: function(data) {
    var objY = $.parseJSON(JSON.stringify(data));
    var objX = $.parseJSON(JSON.stringify(data));
  }
});

Cloning data object in objX & objY are two different object, you do no have to mess up with the "by reference" problem

Gracias!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!