Reputation: 15667
Im using immutableJs
My state object looks like this:
export const initialToolbarState = Map({
temSelectionCtrl : Map({
temSelect : true,
}),
functionalCtrl : Map({
addEle : true,
grpSelect : true,
drawShape : true
}),
operationalCtrl : Map({
zoomIn : true,
zoomOut : true,
pan : true,
temSide : true
}),
referenceCtrl : Map({
saveCtrl : true
})
});
So there are objects with keys which have boolean
values.
I want to map (loop) over these objects & get their keys
. The boolean
values tell whether to render the key
or not. Immutable lets us map over Map
s using its custom map
function. So, the following works, however not as intended:
// map over the initialToolbarState Map object
let ctrls = initialToolbarState.map(( eachToolbar ) => {
// map over the child Map objects like temSelectionCtrl, functionalCtrl, operationalCtrl etc
return eachToolbar.map(( eachCtrl, i ) => {
// get the key corresponding to 'eachCtrl' value
let propKey = eachToolbar.keyOf( eachCtrl );
// propKey is always the first property (1st prop) of 'eachToolbar'
console.log( propKey );
...
Using immutableJs
, is there a way to get the correct key
corresponding to the currect 'eachCtrl' value within the loop? Could I make sure of the i
to help pointing it towards the correct value
for which to match the key
?
Upvotes: 0
Views: 51
Reputation: 432
You can use .map
again on your objects. The second argument is the key, with the full argument signature being (mapper (value: V, key: K, iter: this))
So, this snippet:
initialToolbarState.map(( eachToolbar ) => {
eachToolbar.map((value, key) => {
console.log(key, ' ==> ', value);
});
});
Will log:
temSelect ==> true
addEle ==> true
grpSelect ==> true
drawShape ==> true
// etc…
Now just chain your returns to create the data structure that you need or do whatever with your keys.
Also, reconsider if this “Map of Maps” is the best structure for the problems you are solving. Perhaps a “List of Maps” is better if you need to iterate often. You won’t have instant read/update for individual items, but if your list consists of only a couple of items, then the performance will not suffer.
Upvotes: 1