简体   繁体   中英

Node JS - Object Value Update Strange Behavior

I have a simple object I'm trying to modify and the results are puzzling. This is executed in node.js.

I have an object as follows:

var element = {  
  ident: "value",
  green:
    { date: value2,
      key: value3,
      key2: value4,
      key3: 
       { id1: 
         { p1: [],
           p2: [],
           p3: [],
           p4: [] },
       { id2: 
         { p1: [],
           p2: [],
           p3: [],
           p4: [] },
       { id3: 
         { p1: [],
           p2: [],
           p3: [],
           p4: [] } } },
  red:
    { date: value5,
      key: value6,
      key2: value7,
      key3: 
       { id1: 
         { p1: [],
           p2: [],
           p3: [],
           p4: [] },
       { id2: 
         { p1: [],
           p2: [],
           p3: [],
           p4: [] },
       { id3: 
         { p1: [],
           p2: [],
           p3: [],
           p4: [] } } } };

When I try to set the value of a single "p2" to an array i've filled with some data, each "p2" for that color is set, not just the one referenced. I'm setting the value like so:

element[green].key3[id1][p2] = someArray;

everything in brackets are variables pointing to the key name. The output of the above sets 3 values... all the ids of Green - green.key3.id1.p2, .id2.p2 and .id3.p2 all to the value I only want for green.key3.id1.p2

Any ideas as to what might be happening here? Thanks in advance for the help.

How are you building this object? It may be that you've assigned the same empty array to every p2 in a colour. When you do that each p2 will be a reference to the same array, so pushing a value into one will apparently push that value into each. To test if these are references to the same array, check:

green.key3.id1.p2 === red.key3.id2.p2

if this gives you true , then what I said above is the case. Essentially this is like:

var a = [];
var b = a;
var c = a;

b.push(1); // b = [1], c = [1];
b === c; // true, since they are really references to the same object (array).

EDIT

After rereading, it may be that actually id1 , id2 etc. are assigned to the same object. ie

var id = { p1: [], p2: [], p3: [] };
green.key3.id1 = id;
green.key3.id2 = id;

Like the above, you can test if this is the case by doing:

// true if these are really references to the same object.
green.key3.id1 === green.key3.id2;

If you want a quick way to reuse code without this behavior, then you can do:

function Id() {
    this.p1 = [];
    this.p2 = [];
    this.p3 = [];
}

green.key3.id1 = new Id();
green.key3.id2 = new Id();

Each new Id() will be a new object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM