Mischa
Mischa

Reputation: 3

Pushing a multidimensional array in javascript

Please check down the code below, I want to push an object multiple times into an array and set a specified path. Hope someone can help. TNX!

To keep it simple I just removed all loops and static addressed my array, but still no success and I don't got any idea why:

wrong result:

let myObject = {
"version": "2.0",
"worker": {
    "todo": []
 }
};
let myObjectArray = new Array();
myObjectArray.push(myObject);
myObjectArray.push(myObject);
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);

-> wrong output array


correct result:

let myObjectArray = [
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
},
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
}
];
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);

-> correct output array

Upvotes: 0

Views: 116

Answers (3)

Karthik RP
Karthik RP

Reputation: 1078

If you want to push duplicate items then you need to push different instances of object instead of pushing the object reference.

Just check the below solution, it should be working as desired.

let myObject = {
"version": "2.0",
"worker": {
    "todo": []
 }
};
let myObjectArray = new Array();
myObjectArray.push(JSON.parse(JSON.stringify(myObject)));
myObjectArray.push(JSON.parse(JSON.stringify(myObject)));
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);

Upvotes: 2

Shuja Ahmed
Shuja Ahmed

Reputation: 752

You have to use the deep copying here to make sure the 2 objects are treated as separate instance instead of being the references to the same object.

For "deep" copy, use JSON.parse(JSON.stringify(myObject)) so it will look something like:

myObjectArray.push(JSON.parse(JSON.stringify(myObject)));

Upvotes: 0

SPlatten
SPlatten

Reputation: 5750

The first example, pushes the same object into the array, so you will have a duplicate of the same object in the array, modifying the first instance will also effect the 2nd instance.

In your second example you are creating two separate objects in the array, modifying the first element has no effect on the second.

Objects are always treated as references in JavaScript.

Upvotes: 0

Related Questions