How to clone an object in javascript?

Asked

Viewed 387 times

2

I want to pass an object per function parameter, but I don’t want that object to be changed. For this I want to pass a clone parameter.

Because in javascript, by the tests I did, the object is always passed by reference.

Example:

a = {}
b = a;

b.nome = 'Wallace';

console.log(a, b); //Object {nome: "Wallace"} Object {nome: "Wallace"}

See that the two objects have been changed.

How to do this assignment of b for a in javascript, without keeping the references?

2 answers

3


With Object.create():

Example:

a = {}
b = Object.create(a);
b.nome = 'Gabriel';
a.nome = 'Wallace';
document.write(JSON.stringify(a), JSON.stringify(b))

  • Please use document.write in place of console.log :D

  • @Wallacemaxters For visualization it looks bad, it is [Object][Object]..

  • Just give JSON.stringify my friend :D

  • 1

    Gabriel, you know why data stays inside __proto__ when you wear it like that?

  • @Wallacemaxters I’m not 100% sure, but I think it’s Inheritance. if you create an item in the object to you will see that b will inherit it, o a não tera proto but the b will have

  • This method is not the best alternative.

  • @devgaspa Could elaborate a response by making the comparison ?

Show 2 more comments

1

I was able to clone through the method $.extend jQuery.

Behold:

a = {}

b = $.extend({}, a);

b.nome = 'Teste';


document.write(JSON.stringify(a), JSON.stringify(b))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.