how to use 'getOwnPropertyNames' to iterate through contents of a map

纵饮孤独 提交于 2020-11-29 10:49:27

问题


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
});

回答1:


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);
}


来源:https://stackoverflow.com/questions/47670143/how-to-use-getownpropertynames-to-iterate-through-contents-of-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!