Set Object to Object Without Pointer Javascript [duplicate] - javascript

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 1 year ago.
In my program, I have 2 objects, A and B, with some code like this:
var a = {"color":"blue"};
var b = a;
a.color = "orange";
console.log(b.color);
By setting B to A, they point to the same memory, and I don't want them to do that. I thought of running a for loop of all the keys and values, setting them individually to B, but there's got to be a better way. Any ideas?

You can use spread syntax to clone the object.
But remember it is just a shallow copy
var a = {
color: "blue"
};
var b = { ...a };
b.color = "red";
console.log(a);
console.log(b);
console.log(a.color);
console.log(b.color);

There are libraries, like lodash, with clone functions, but for a simple, shallow cloning, you can use:
let b = Object.assign({}, a);

Related

How to copy one object to another variable without passing refrence in javascript [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I have one object
var a = {b:{c:{d:{e:1}}}}
I want to copy that object to another variable b, without passing a reference, so I try spread operator
var b = {...a}
It is not removing reference at a deep level, as I change the value in the object "a" it also changes the value in the object "b"
a.b.c.d.e = 2
console.log(b.b.c.d.e)
it give output 2 instead of 1
var a = {b:{c:{d:{e:1}}}};
var b = {...a};
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)
How can I handle this issue
I've always done this to copy JSON objects. Works great IMO there may be a better way out there.
var a = {b:{c:{d:{e:1}}}};
var b = JSON.parse(JSON.stringify(a));
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)

How return copy from .find JS? [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I have the following code:
let a = this.menu.getMenuItems().find((item) => item.$entityType === val);
let b = Object.assign({}, a);
this.dictChildren = b.children.map((item) => {
});
First I try to find element in array then create copy.
After I attempted to modify found element using map(), despite
let b = Object.assign({}, a);
It modifies original array.
How map only copied object b?
Object.assign makes a shallow copy and not a deep copy.

JS Make deep copy of array [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 4 years ago.
Is there any way I can make a deep copy of a variable? (NOT object). Example:
var a = ["String", "string"];
var b = a;
b.splice(1, 1);
b = a;
In my example, a isnt supposed to change, I want to use it later for restoring b. (As showed in code above).
I understand that = just makes a new reference, hence the question: is there any other way I can make a deep copy instead of a reference?
Want to note that I can't be using any library, I've found answers suggesting jQuery and such, but I cannot use this.
Have you tested your code? Numbers and other primitives are copied, not referenced.
var a = 1;
var b = a;
console.log(`a is ${a}`);
console.log(`b is ${b}`);
b++;
console.log(`a is ${a} (no change)`);
console.log(`b is ${b}`);
After your edit with a different example:
var a = ["foo", "bar"];
var b = a.slice(); // array copy
console.log(`a is ${a}`);
console.log(`b is ${b}`);
b.splice(1, 1);
console.log(`a is ${a} (not changed)`);
console.log(`b is ${b}`);
b = a;

Storing value in two variables and changing one affects both variables in Javascript [duplicate]

This question already has answers here:
How does variable assignment work in JavaScript?
(7 answers)
Closed 7 years ago.
I have an object "a" and would like to duplicate it to "b"
When I delete an element in "a" why is "b" also being affected?
var a = {'apple':1,'orange':2,'grapes':3}
var b = a
console.log(a,b)
delete b.apple
console.log(a,b)
Now a and b are the same. I only want the element in b to be deleted.
How can I do this
Objects and arrays in javascript are references. So when you do:
var b = a;
You're making another pointer to object a. You're not copying a.
If you want to make a copy of an object you can use Object.create:
var b = Object.create(a);

How to update one Javascript object array without updating the other [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 8 years ago.
I created an object array with some values. Then I created another object array and initialized it with the first one. Then I pushed a value in 2nd array, and console logged both arrays. Both arrays had same value. Why is this happening and how can we stop this?
My Code:
var a = { "filters": [] }; // 1st object array
var keyValue = {};
// pushed 2 values in "a" array
keyValue["abc"] = "123";
a.filters.push(keyValue);
keyValue["def"] = "456";
a.filters.push(keyValue);
var b = a; // created another object array & initialized it with "a" array
var keyValue1 = {};
// pushed 1 value in "b" array
keyValue1["ghi"] = "789";
b.filters.push(keyValue1);
console.log(a);
console.log(b);
This prints same values for a and b.
How do I push values into 2nd array without updating 1st one?
Assignment such as var b = a for a object creates an object 'b' which references(just like pointer) the same location pointed by 'a', in general. You may find this link helpful.
However you can create/clone a new array with slice method. var b = a.slice()
You can use
var b = JSON.parse(JSON.stringify(a));
https://stackoverflow.com/a/4591639/1623259
Both are pointing to the same values in the memory when you say:
var b = a;
So if you change a, b will be affected and vice versa, you need to copy using a loop.
EDIT
use this line of code which I get from this post
var b= a.slice(0);

Categories

Resources