Advendra Deswanta
Advendra Deswanta

Reputation: 1

Javascript - How to make all object items set with different values?

NOTE: This is the first question that I ever created in StackOverflow.

I was trying to implement layer manager in javascript with this value:

var layers = [
    {
        id: "layer_1",
        name: "Layer 1",
        child: [
            {
                id: "layer_1A",
                name: "Layer 1A",
                child: [
                    {
                        id: "layer_1A1",
                        name: "Layer 1A1"
                    },
                    {
                        id: "layer_1A2",
                        name: "Layer 1A2"
                    }
                ]
            },
            {
                id: "layer_1B",
                name: "Layer 1B"
            }
        ]
    },
    {
        id: "layer_2",
        name: "Layer 2"
    },
    {
        id: "layer_3",
        name: "Layer 3"
    }
]

and save the result into this:

var indexSelector = {};

here is the code:

var value = [-1];

function read_layers(obj) {
    // Checks the array (layer/child)
    if (Array.isArray(obj)) {
        for (let layer of obj) {
            read_layers(layer);
        }
    }
    // Checks the object
    else if (typeof obj == "object") {
        for (let layer of Object.entries(obj)) {
            // Checks the childs
            if (layer[0] == "layers" || layer[0] == "child") {
                value.push(-1);
                read_layers(obj[layer[0]]);
                value.pop()
            }
            // Checks the object keys
            else if (layer[0] == "id") {
                if (!indexSelector.hasOwnProperty(layer[1])) {
                    ++value[value.length-1];
                    indexSelector[layer[1]] = value; // Result
                }
            }
        }
    }
}

read_layers(layers);

I want the expected result to looks like this:

{
  layer_1: [ 0 ]
  layer_1A: [ 0, 0 ]
  layer_1A1: [ 0, 0, 0 ]
  layer_1A2: [ 0, 0, 1 ]
  layer_1B: [ 0, 1 ]
  layer_2: [ 1 ]
  layer_3: [ 2 ]
}

But here is the problem result:

{
  layer_1: [ 2 ]
  layer_1A: [ 2 ]
  layer_1A1: [ 2 ]
  layer_1A2: [ 2 ]
  layer_1B: [ 2 ]
  layer_2: [ 2 ]
  layer_3: [ 2 ]
}

How to fix this problem with different object values? Thanks.

Upvotes: 0

Views: 65

Answers (1)

coding monster
coding monster

Reputation: 394

NOTE: All assignment (with operator = ) of objects is applied with theirs reference, in javascript, like in as java.

So, at line indexSelector[layer[1]] = value; // Result , the value is assigned with its reference, not the whole value.

That's why the values of the result are all same.

Solution: Use indexSelector[layer[1]] = Object.assign({}, value);.

It'll solve your problem.

Upvotes: 1

Related Questions