Search code examples
javascriptdestructuringcomputed-properties

JavaScript: Object destructuring dynamically via computed keys


I'm trying to write a curried function dissoc, that takes in a prop and an object and removes the key and its value from the object.

Here is the code that works:

const dissoc = prop => obj => {
  const result = {};
  for (let p in obj) {
    result[p] = obj[p];
  }
  delete result[prop];
  return result;
};

Now, I thought this could be written more concise by using computed properties, destructuring and the rest operator:

const dissoc = prop => ({ [prop], ...obj}) => obj

But this code throws with:

Uncaught SyntaxError: Unexpected token ,

So I tried:

const dissoc = prop => ({ prop, ...obj}) => obj

which computes, but just returns the object without the prop.

Is there a way to dynamically destructure and / or simplify this code?


Solution

  • You need a target variable, for example an underscore as sign for an unused variable/placeholder.

    const dissoc = prop => ({ [prop]: _, ...obj}) => obj
    

    Javascript does not have the concept of using variable variables, like PHP with $$variable, where the value of $variable is taken as variable. In this case, you need another variable, because of the computed property name and without a real variable, it does not work.

    Maybe worth a read: Object property assignment pattern [YDKJS: ES6 & Beyond]