1

I have the map posted below in the code section. I added some values to the map as shown.But when i tried to display the contents of the map using 'getOwnPropertyNames' as shown in th code, the log statement in the loop does not display any thing.

please let me know how to utilize 'getOwnPropertyNames' properly

code:

const mymap = new Map();

const mapKeyToValue = (key, value) => {
  mymap.set(key, value);
};

const getMyMap = () => mymap;

mapKeyToValue('1', [{ 'a': 10, 'b': 100, 'c': 1000 }]);
mapKeyToValue('2', [{ 'a': 20, 'b': 200, 'c': 2000 }]);
mapKeyToValue('3', [{ 'a': 30, 'b': 300, 'c': 3000 }]);
mapKeyToValue('4', [{ 'a': 40, 'b': 400, 'c': 4000 }]);


console.log(Object.getOwnPropertyNames(mymap));//displays []

Object.getOwnPropertyNames(mymap).forEach( (v) => {
  console.log(mymap[v]);//displays nothing
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • 1
    What is your goal in using `getOwnPropertyNames` ? – ChrisR Dec 06 '17 at 08:51
  • @ChrisR actually, in another code i have a map or it could be an array, and i donot have any knowledge about key it comprise..so i decided to make a test to learn how can i iterate through keys in a map – Amrmsmb Dec 06 '17 at 08:58

1 Answers1

3

A map does not have properties (which would be limited to string and symbol keys). It stores its elements on the inside. To iterate through a Map, use its entries, values, keys, or implicit iterator methods with a for … of loop:

for (const [key, value] of mymap) {
    console.log(key, value);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • so, getOwnPropertyNames should be only used with arrays? – Amrmsmb Dec 06 '17 at 09:08
  • Uh, `getOwnPropertyNames` should not even be used with arrays. Arrays are iterated with standard `for (let i=0; i – Bergi Dec 06 '17 at 09:09
  • would you please tell me, which data structure i should use getOwnPropertyNames with? – Amrmsmb Dec 06 '17 at 09:11
  • @LetsamrIt It's meant as a reflection method for arbitrary objects (mostly those where `for … in` doesn't fit because of enumerability), not necessarily for something used as a data structure. – Bergi Dec 06 '17 at 09:13
  • @ChrisR It's not a prototype method – Bergi Dec 06 '17 at 09:15
  • Wooooops, my bad, indeed. Link to the doc, so we're clear => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames – ChrisR Dec 06 '17 at 09:18
  • thanx..but is there any way in javascript to determine if the object in hand is an array or a map?? – Amrmsmb Dec 06 '17 at 09:21
  • 1
    @LetsamrIt Sure, `Array.isArray(x)` and `x instanceof Map` ([or worse](https://stackoverflow.com/a/29926193/1048572)) will do. In general you should design your code so that you know which type a variable has, though. – Bergi Dec 06 '17 at 09:23