Hacker News new | ask | show | jobs
by thih9 396 days ago
About pain points / feature requests:

Is there an idiomatic way to duplicate a hash while replacing one of its values, preferably something that supports nesting?

Whenever I work with react and immutable structures, this comes up and I hack something simple.

I don’t do FE on a regular basis though so my perspective may be skewed.

2 comments

These days that's pretty well-supported in the base language:

    const updated = { ...existing, someKey: someNewValue };
You mention nesting. That starts to look messier:

    const updated = { ...existing, someKey: { ...existing.someKey, ...someNewValue } };

There's a whole cottage industry of little libraries to make this ergonomic/fast in the general case (copying immutable objects with nested changes). `immer` is a popular choice. But the reality is that it gets complicated to do this generically; in my view it's usually better to just use the base language where possible, even if it means sprouting some util functions for the various kinds of updates you end up doing.
There might be a function called produce in one of your immutable/react lib.