1

I'm trying to use a map instead of an object for some data that I'd like to have complex keys. Since I can use an object as a key in a map, this seems cleaner to me than having an object key that is a stringified and concatenated key eg,

const datum = {
  large: 'chunk', 
  of: 'data'
}
const ids = [10797, 11679, 10679, 10160, 11681, 01802]
const view = 142171
const selectedDateRange = 'ONE_MONTH'
const objKey = {
  ids,
  view,
  selectedDateRange
}
const data = new Map()
data.set(objKey, datum)
console.log(data.get(objKey)) // this works and i see the data
const objKeyRef = objKey
console.log(data.get(objKeyRef)) // also works and i see the data

However it won't work if the key given to get doesn't === the key it was set with.

data.get({
  ids,
  view,
  selectedDateRange
}) // undefined

This is clear in the documentation (though i don't really see it explained why). I'm wondering if there is a way around it. I'd like to be able to compose the keys at a later time and get their value from the map.

Is there any way to get a value from a map without access to an object that === the key used to set it?

1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

0

If the objects are serializable, you can JSON#stringify the object. Since it's a string, you it will we work when you'll assemble it in the future.

const datum = {
  large: 'chunk', 
  of: 'data'
}
const ids = [10797, 11679, 10679, 10160, 11681, 01802]
const view = 142171
const selectedDateRange = 'ONE_MONTH'
const objKey = {
  ids,
  view,
  selectedDateRange
}
const data = new Map()

data.set(JSON.stringify(objKey), datum)

const result = data.get(JSON.stringify({
  ids,
  view,
  selectedDateRange
}))

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • yes in that case I could just use an object I suppose, no? When an object is stringified is it always certain to produce an identical string? I know that objects' iteration order is not certain in a `for...in`, I'm curious if that would also be a concern here. – 1252748 Jun 21 '17 at 17:28
  • Indeed you can use an object. The iteration order is the same as the [insertion order](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map#Description). – Ori Drori Jun 21 '17 at 17:30