how to pass by value in Javascript

Asked

Viewed 241 times

1

I have the following situation:

let a=[{nome:"oi"},{nome:"xau"}]
let b=Object.assign([], a)

b[0].nome=5

console.log(b) //[{nome:5},{nome:xau}]
console.log(a) //[{nome:5},{nome:xau}]

A little while ago I asked here how to pass values without reference, I was told to use Object.assing, but still it is not working, someone can help me as I would change the b[0]. name without changing the a?

  • Have you tried using the same a, in the first assign parameter?

  • type Object.assign([{}],a)? I’ve tried this and it didn’t work

3 answers

5


The method assign makes a blank copy, ie copies the attribute values that are from the object, but whatever reference it copies the reference value. In your example a contains two references and is therefore not working.

The suggestion I thought could help would be to use:

var b = JSON.parse(JSON.stringify(a))

3

One solution is to serialize the object and deserialize in a new one using JSON, thus:

let b=JSON.parse(JSON.stringify(a))

let a=[{nome:"oi"},{nome:"xau"}]
let b=JSON.parse(JSON.stringify(a))

b[0].nome=5

console.log(b[0]) //[{nome:5},{nome:xau}]
console.log(a[0]) //[{nome:5},{nome:xau}]

EDIT: @Everson pointed out about explaining better the reason for serializing/deserialize:

Serialize transforms object into stream, in the case of a JSON string, which will "break" the reference to the original object, and deserialize transforms it back into object, which the reference, creating a new object

  • Serialize transforms object into stream, in this case a string JSON, which will "break" the reference to the original object, and deserialize it transforms again into object, which reference, creating a new object

  • 1

    Put it in the answer, please.

  • Done @Everson thanks

1

What you need is to make a Deep copy.

Other than Shallow copy or blank copy (explained in the reply of prmottajr), you need a copy that is created without any reference to the original data, which is applicable to the object arrays for example.

Solution creating a method:

(method that will create a new object and copy the properties to that object)

var a=[{nome:"oi"},{nome:"xau"}]
var b = Clonar(a);

b[0].nome=5;

console.log(a, b);

function Clonar(source) {
    if (Object.prototype.toString.call(source) === '[object Array]') {
        var clone = [];
        for (var i=0; i<source.length; i++) {
            clone[i] = Clonar(source[i]);
        }
        return clone;
    } else if (typeof(source)=="object") {
        var clone = {};
        for (var prop in source) {
            if (source.hasOwnProperty(prop)) {
                clone[prop] = Clonar(source[prop]);
            }
        }
        return clone;
    } else {
        return source;
    }
}

Solution with Jquery:

var a=[{nome:"oi"},{nome:"xau"}]
var b = jQuery.extend(true, {}, a);

b[0].nome=5;
console.log(a, b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As it has already been quoted in other answers. Solution Creating and deserializing:

let a=[{nome:"oi"},{nome:"xau"}]
let b=JSON.parse(JSON.stringify(a))

b[0].nome=5

console.log(a,b)

Sources:

Browser other questions tagged

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