简体   繁体   中英

How to access an (array) key in a JavaScript Map?

I'm looping through a two-dimensional array to set the values to a map. I'm storing the [i,j] indices as the map key, and the actual arr[i][j] value as the map value:

const arrMap = new Map()

for(let i = 0; i < arr.length; i++){
        for(let j = 0; j < arr[i].length; j++){
            arrMap.set([i,j],arr[i][j]);
        }
    }

At this point I've "console-logged" the Map, and it seems to have set correctly with pairs like the following: [0,0] => "A" . Then I try to access the map value: arrMap.get([0,0]) but this returns undefined. How can I access the "A" from my arrMap?

Example array that I'd be looping through would be [ ["A","B","B"],["A","A","A"] ]

There's a very similar question here- Array as a javascript map's key? but the answer didn't make sense to me.

If you read the answer to the other question carefully, you'll see that what are you are trying to do cannot work as the array [0,0] that you are trying to fetch with is not the same array [0,0] that you set with. You could perhaps consider stringifying the array key. For example:

 const arrMap = new Map(); const arr = [ [1, 2, 3], [4, 5, 6] ]; for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { arrMap.set(JSON.stringify([i, j]), arr[i][j]); } } console.log(arrMap.get(JSON.stringify([1, 1]))); // 5

Because of the nature of an object and the uniqueness of only same object references, you need a wrapper to access the values for storing and retrieving.

The wrapper builds a primitive value (string) and does not rely on object references.

 const wrapper = array => array.join('|'), arr = [["A", "B", "B"], ["A", "A", "A"]], arrMap = new Map(); for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { arrMap.set(wrapper([i, j]), arr[i][j]); } } console.log(arrMap.get(wrapper([0, 0]))); // A

Your key [0, 0] is a reference type. So every time while you write the same array, you are creating a new reference. Map does not have such reference and this is reason why you are getting undefined . Try to use a primitive type as a key.

You can use keys() method to see all keys in your Map data structure, then you can access by desired key:

You can use primitive value as a key because every time you access to value by declaring array, you are creating a new reference. And it means that your Map object does not have a key with new reference:

 const arrMap = new Map() let arr = [[1, 2, 3], [4, 5, 6], [7]] for(let i = 0; i < arr.length; i++){ for(let j = 0; j < arr[i].length; j++){ arrMap.set(`${i}, ${j}`,arr[i][j]); } } for (let key of arrMap.keys()) { console.log(`key: `, key); console.log(`result: `, arrMap.get(key)); } let result = arrMap.get('0, 0'); console.log('The value by key of primitive type: ', result);

convert key to string

arrMap.set([i,j].toString(),arr[i][j]);

here you can iterate over to fetch key and value

 for(let [value,key] of arrMap){
     console.log(value)
     console.log(key)
    }

if you want to access directly

arrMap.get('0,0')

The answer which you referring to is, that the Map key will be the key of the array. So if you have an array to set as key, it needs to be an array itself so the map is able to retrieve its key.

I build you a working example.

 const map = new Map() map.set([0, 0], 'A') const keyZ = [2, 2] map.set(keyZ, 'Z') console.log(map.get([0, 0])) // will not find console.log(map.get(keyZ)) // will output Z const keyA = [0, 0] map.set(keyA, 'A') console.log(map.get(keyA)) // will output A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM