mhm
mhm

Reputation: 194

Javascript Map returns undefined although (key, value) pair defined

I am running this code snippet in linux terminal using nodejs. Although the (key, value) pair is correctly set, the code prints undefined. Any explanation or work around for this problem?

function trial() {
    var obj1 = {};
    var obj2 = {};
    obj1.fund = 1;
    obj1.target = 2;
    obj2.fund = 1;
    obj2.target = 2;
    states = [];
    states.push(obj1);
    states.push(obj2);
    actions = [1,2,3,4];
    table = new Map();
    for (var state of states) {
        for (var action of actions) {
            cell = {};
            cell.state = state;
            cell.action = action;
            table.set(cell, 0);
        }
    }
    var obj = {};
    obj.state = states[1];
    obj.action = actions[1];
    console.log(table.get(obj));   
}

Upvotes: 0

Views: 3092

Answers (2)

Carr
Carr

Reputation: 2771

You need the original object reference to match the key in table(Map()), let's hold every new cell which is each object reference to show that.

And even you have a deep clone of object, to Map(), it is not the same key.

     var obj1 = {};
     var obj2 = {};
     obj1.fund = 1;
     obj1.target = 2;
     obj2.fund = 1;
     obj2.target = 2;
     states = [];
     states.push(obj1);
     states.push(obj2);
     actions = [1,2,3,4];
     table = new Map();
     var objRefs = [];
     var count = 0;
     for (var state of states) {
         for (var action of actions) {
             cell = {};
             cell.state = state;
             cell.action = action;
             table.set(cell, count);
             objRefs.push(cell);  //hold the object reference
             count ++;
         }
     }
     
     for (var i = 0; i < objRefs.length; i++) {
       console.log(table.get(objRefs[i]));
     }

     // Copy by reference
     var pointerToSecondObj = objRefs[1]; 
     
     console.log(table.get(pointerToSecondObj));
     
     //Deep clone the object
     var deepCloneSecondObj =  JSON.parse(JSON.stringify(objRefs[1]));
 
     console.log(table.get(deepCloneSecondObj));

Upvotes: 1

JohnPan
JohnPan

Reputation: 1210

Try this one. You will probably get what you need. I did a small beautify.

function trial() {
    var obj1 = {
            fund: 1,
            target: 2
        },
        obj2 = { 
            fund: 1,
            target: 2
        },
        obj = {},
        states = [
            obj1, obj2
        ],
        actions = [1,2,3,4],
        table = new Map(),
        cell
    ;
    for (var state of states) {
        for (var action of actions) {
            cell = {};
            cell.state = state;
            cell.action = action;
            table.set(cell, 0);   
        }
    }
    obj.state = states[1];
    obj.action = actions[1];
    return(obj);
    //console.log(table.get(obj));   
}
console.log(trial())

Upvotes: 0

Related Questions