Cloud9c
Cloud9c

Reputation: 329

How to find value of key if the key is an array?

I'm trying to make the dictionary as coordinates that return colors.

I made a dictionary with the keys as an array, like [0, 1]. However, I am unable to get the value through giving the key.

dict = {
  key:   [0, 1],
  value: "red"
}

dict[[0, 1]]

I expected dict[[0, 1]] to give the value "red", however it just says "undefined".

Upvotes: 0

Views: 108

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

For using an array as key, you might use a Map with the object reference to tha array as key.

This approach does not work for similiar but unequal array.

var map = new Map,
    key = [0, 1],
    value = 'red';

map.set(key, value);

console.log(map.get(key));    // red
console.log(map.get([0, 1])); // undefined

For taking a set of coordinates, you could take a nested approach.

function setValue(hash, [x, y], value) {
    hash[x] = hash[x] || {};
    hash[x][y] = value;
}

function getValue(hash, keys) {
    return keys.reduce((o, key) => (o || {})[key], hash);
}

var hash = {},
    key = [0, 1],
    value = 'red';

setValue(hash, key, value);

console.log(getValue(hash, key));
console.log(hash);

Or a joined approach with a separator for the values.

var hash = {},
    key = [0, 1].join('|'),
    value = 'red';

hash[key] = value;

console.log(hash[key]);
console.log(hash);

Upvotes: 3

Related Questions