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

I'm looping through a two-dimensional array to set the values to a map. I'm storing the [i,j]

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.

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.

Share Improve this question asked Jul 29, 2020 at 6:44 Tzvi2Tzvi2 1823 silver badges17 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 2

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

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')

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744121701a4559431.html

相关推荐

  • How to access an (array) key in a JavaScript Map? - Stack Overflow

    I'm looping through a two-dimensional array to set the values to a map. I'm storing the [i,j]

    8天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信