webmato
webmato

Reputation: 2171

what is the best way to delete mutiple nested keys from Immutable.js Map

Is in the Immutable.JS any feature how to delete multiple keys from a Map?

Lets say I want delete all nested keys c0, c1, c2 from the Immutable map in this example:

const x = fromJS({
  a1: 'A',
  a2: { b: { c0:'C0', c1:'C1' } },
  a3: { b:'B' },
  a4: { b: { c:'C', c1:'C1', c2:'C2' }},
  a5: { b: { c: { d:'D', d1:'D1' }}},
  a6: { b: { c2:'c2' }},
});

Is there any simple pure way how to do that?

My solution is this:

const { fromJS, Map } = Immutable;

const x = fromJS({
  a1: 'A',
  a2: { b: { c0:'C0', c1:'C1' } },
  a3: { b:'B' },
  a4: { b: { c:'C', c1:'C1', c2:'C2' }},
  a5: { b: { c: { d:'D', d1:'D1' }}},
  a6: { b: { c2:'c2' }},
});

console.log(x.toJS());

const newX = x.map((value, key) => {
  if (Map.isMap(value)){
    value = value.hasIn(['b', 'c0']) ? value.deleteIn(['b', 'c0']) : value;
    value = value.hasIn(['b', 'c1']) ? value.deleteIn(['b', 'c1']) : value;
    value = value.hasIn(['b', 'c2']) ? value.deleteIn(['b', 'c2']) : value;
  } 
  return value;
});

console.log('----------------------------');
console.log(newX.toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>

But I don't like the variable reassigning in value = value.hasIn(... nor ESLint.

Upvotes: 3

Views: 2037

Answers (1)

zerkms
zerkms

Reputation: 254916

You don't need to check if the path exists ("If any keys in keyPath do not exist, no change will occur.", see the links below), so simply chain the calls

return value.deleteIn(['b', 'c0']).deleteIn(['b', 'c1']).deleteIn(['b', 'c2']);

Additionally, when you make multiple mutations it may be beneficial to use withMutations:

return value.withMutations(map => {
    map.deleteIn(['b', 'c0']).deleteIn(['b', 'c1']).deleteIn(['b', 'c2']);
});

References:

Upvotes: 5

Related Questions