Typescript map.get return undefined

Viewed 36913

When I want get Object by key I have undefined each all element.

My Map :

nodesMaps : Map<number, Object> = [
{ key: "1", value: Object },
{ key: "2", value: Object },
{ key: "3", value: Object },
]

When I want get value of this map :

this.nodesMaps.get(1) // return undefined
this.nodesMaps.get("1") // return undefined
3 Answers

You've messed many things.

  1. Even if you declared type Map, you assigned an Array value.
  2. The array was array of objects, not array of arrays with length 2. etc.

Valid map creation should look like this:

let nodesMap = new Map([
    [1, 'foo'],
    [2, 'bar'],
    [3, 'baz'],
])
    
 console.log(nodesMap.get(1)) // foo

You can't assign properties on top of the fact they aren't objects, they are arrays, and you need to use new. Your code should look like:

// TypeScript
nodesMaps : Map<number, Object> = new Map([
  [ 1, Object ],
  [ 2, Object ],
  [ 3, Object ],
]);

Map Reference

var nodesMaps = new Map([
  [ 1, "Object 1" ],
  [ 2, "Object 2" ],
  [ 3, "Object 3" ],
]);

$('button').on('click', function() {
  var key = $(this).data('key');
  console.log("key :" + key);
  console.log("value: " + nodesMaps.get(key));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-key="1">1</button>
<button data-key="2">2</button>
<button data-key="3">3</button>

Related