“Clon un objeto JavaScript” Código de respuesta

objeto clon en js

var student = {name: "Rahul", age: "16", hobby: "football"};

//using ES6
var studentCopy1 = Object.assign({}, student);
//using spread syntax
var studentCopy2 = {...student}; 
//Fast cloning with data loss
var studentCopy3 = JSON.parse(JSON.stringify(student));
JavascriptNinja

Clon un objeto JavaScript

var sheep={"height":20,"name":"Melvin"};
var clonedSheep=JSON.parse(JSON.stringify(sheep));

//note: cloning like this will not work with some complex objects such as:  Date(), undefined, Infinity
// For complex objects try: lodash's cloneDeep() method or angularJS angular.copy() method
Grepper

La mejor manera de clonar un objeto en JavaScript

const person = {
    firstName: 'John',
    lastName: 'Doe'
};


// using spread ...
let p1 = {
    ...person
};

// using  Object.assign() method
let p2 = Object.assign({}, person);

// using JSON
let p3 = JSON.parse(JSON.stringify(person));
Repulsive Raven

Asignación del objeto MDN

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
Worrisome Wallaby

Respuestas similares a “Clon un objeto JavaScript”

Preguntas similares a “Clon un objeto JavaScript”

Más respuestas relacionadas con “Clon un objeto JavaScript” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código