Im a bit confused about this and cant seem to work this out.
Say I have this:
const AnObj = Immutable.Map({
a : "a",
b : Immutable.List.of(
a,
b,
c,
Immutable.Map({
a : "a"
})
)
});
With Immutable Maps, we use strings within get()
to find the corresponding properties. How do we read array values?
Im a bit confused about this and cant seem to work this out.
Say I have this:
const AnObj = Immutable.Map({
a : "a",
b : Immutable.List.of(
a,
b,
c,
Immutable.Map({
a : "a"
})
)
});
With Immutable Maps, we use strings within get()
to find the corresponding properties. How do we read array values?
2 Answers
Reset to default 7 +50Disclaimer - This applies to all Immutable types, not just List.
Several ways -
The
get
method -AnObj.get('b').get(3).get('a')
(Thanks @stas). This is useful when the structure is not very deep. As you see, the syntax is very verbose.The succinct
getIn
-AnObj.getIn(['b', 3, 'a'])
I love this because this pattern allows having a generic getter and I can toss the key-path around to the various ponents.The veritable valueSeq/entrySeq, when you want all the values and don't care for indices -
AnObj.get('b').valueSeq()
This is useful when the list is huge and you want to delay the iteration until its absolutely needed. This is the most performant of them all.
You can pass numeric zero-based indexes to List.get()
:
AnObj.get('b').get(3).get('a')
See https://facebook.github.io/immutable-js/docs/#/List/get.