1

If it was as part of a code block, I could do this:

const obj = {a: 1, b: 2};
delete obj.a;
console.log(obj);

Or this:

const {a, ...rest} = {a: 1, b: 2};
console.log(rest);

Is there a way to do this in an expression? Like this (pseudocode!):

console.log(Object.removeProperty({a: 1, b: 2}, 'a'));

Context / use case

I am aware of How do I remove a property from a JavaScript object? but the answers always seem to use statements, not expressions.

I want expressions as I'm in a middle of mapping one object to another, like this:

function mapSomethingToSomethingElse(obj) {
  return {
    prop1: obj.prop1,
    prop2: obj.prop2,
    prop3: {
      ...Object.removeProperty(obj.prop3, 'a') // <- HERE
      abc: def,
    },
    // ...
  }
}

I can hide the statements into a helper function, that's always an option, but in my specific case, I'd be happy enough with in-line expression if one can be written in JavaScript.

Borek Bernard
  • 50,745
  • 59
  • 165
  • 240
  • 3
    `delete obj.a` is already an expression. You can use `const result = (delete obj.a, obj);` if you really need the `result` alias. Otherwise just use `delete obj.a` and keep `obj` since it’s the same object, anyway. – Sebastian Simon Oct 10 '19 at 14:56
  • What would the return value be? – IceMetalPunk Oct 10 '19 at 14:57
  • 3
    Why do you want to remove a property with a function? What's wrong in using `delete`? Are you considering the trivial solution of just defining a custom function? – Christian Vincenzo Traina Oct 10 '19 at 14:58
  • Are you looking for object to be immutable? (maybe look into a library such as immutable.js) – Seth McClaine Oct 10 '19 at 14:59
  • To be clear, `delete` is an *operator* in the expression grammar. – Pointy Oct 10 '19 at 14:59
  • 1
    @SethMcClaine No, this question is about how to delete object properties in an expression context, not how to make objects immutable (which you can already do by `Object.freeze` without the library). – Sebastian Simon Oct 10 '19 at 15:01
  • create your own delete function which returns the objects – oygen Oct 10 '19 at 15:04
  • Thanks all, I've updated the OP to provide a little bit more context but I'd rather focus on the technicality of it as I'd use such construct in other places as well. – Borek Bernard Oct 10 '19 at 15:16

1 Answers1

0

Looking at the documentation for an object:

Deleting a property from an object: There isn't any method in an Object itself to delete its own properties (e.g. like Map.prototype.delete()). To do so one has to use the delete operator.

Maria
  • 295
  • 2
  • 11
  • 3
    But there is [`Reflect.deleteProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty). – Sebastian Simon Oct 10 '19 at 15:03
  • @SebastianSimon Oh cool, you should post that as an answer. Didn't know that existed. – Maria Oct 10 '19 at 15:05