0

Let's say I have data which is an object with some keys.

I also have context and contextId which both are string, but context might be null or undefined.

How to created a new object that clones data and adds data[context] = contextId only to it when context is not null or undefined in a one-liner using es6+.

Christiaan Westerbeek
  • 10,619
  • 13
  • 64
  • 89
  • 1
    Here's the answer that I was just typing out and I couldn't find anywhere else. I don't get why this got closed. `let newData = { ...data, ...(context && { [context]: contextId })}` – Christiaan Westerbeek Jun 05 '20 at 12:00
  • 1
    @ChristiaanWesterbeek Your approach and answer above are practically the same. Flag being some boolean value, context or contextId makes not difference. Written with multiple aditional values or a single one, the approach is the same. – noitse Jun 05 '20 at 12:17
  • @ChristiaanWesterbeek There's no difference in whether the property key is computed or not, the strategy to make the property optional is exactly the same. – Bergi Jun 05 '20 at 12:48
  • 1
    Thanks for teaching me when a question is too similar to another. I'll remember to reframe from posting next time in such cases. I just liked the one-liner for this specific case so much that I wanted to give it some attention – Christiaan Westerbeek Jun 05 '20 at 12:51

0 Answers0