1

To update nested data with immutability helper, you usually hard-code the path to the data you want to update, sometimes with variables for keys. What do you do if the number of keys/indexes (that is, the depth of nesting) is also variable? I'm looking for a way to update data given an arbitrarily long list of keys. Given [0, 1, 1], I want to update data[0][1][1], or given [9], I'd like to update data[9].

Context: I have a deeply nested array of comments, where a nested comment is a reply to its parent, and I need to add/remove/edit comments based on which comment is selected.

It looks like Immutable.js has methods that work just like I'm describing:

Immutable.JS’s get() or getIn() methods … [access] properties via an array of strings, each of which represents a property key.

https://redux.js.org/recipes/using-immutablejs-with-redux#difficult-to-interoperate-with

Is there a good way to do this with immutability-helper? If not, it's not too late for me to switch to Immutable.js.

Qaz
  • 1,556
  • 2
  • 20
  • 34

1 Answers1

0

The helpers can be used on arbitrary objects, not just immutables. These include getIn, setIn, and updateIn:

Take a look at the docs, they are quite convinient and come with samples.

const { getIn } = require('immutable');

const myDynamicPath = [0, 1, 1];
getIn({ 1: { 2: { 3: 123 }}}, [1, 2, '3'], 'ifNotSet') // 123

PS: Take care when using numbers as keys, as they are always strings on objects. ImmutableJS (and native Map/Set) on the other hand can deal with arbitrary types in keys and are therefore type-strict when used on ImmutableJS collections. So if you ever convert that data object to an Immutable, you might have confusing results if you do not pay attention.

dube
  • 4,898
  • 2
  • 23
  • 41