0

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".

Cloud9c
  • 219
  • 5
  • 16
  • Is `dict` is an array of objects? – Eddie Apr 06 '19 at 16:10
  • 1
    What exactly are you expecting to return? This is very confusing. And you are confusing property values with property keys – charlietfl Apr 06 '19 at 16:12
  • Are you sure this is JavaScript? – Lazar Ljubenović Apr 06 '19 at 16:13
  • I'm trying to make the dictionary as coordinates that return colors. – Cloud9c Apr 06 '19 at 16:14
  • 2
    Need to be a lot more specific than that about what you are trying to accomplish – charlietfl Apr 06 '19 at 16:15
  • this is a bad idea for reasons explained here: https://stackoverflow.com/questions/10173956/how-to-use-array-as-key-in-javascript essentially you seem to have a misunderstanding of how objects in js work, and are attempting to use an array as a key, which is a very bad idea for reasons in the linked answer. – bryan60 Apr 06 '19 at 16:23
  • @Cloud9c if `dict` is a dictionary, can you provide a sample of that variable with a lot of data on it. – Eddie Apr 06 '19 at 16:24

1 Answers1

3

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392