Lodash: clone without

Sometimes it’s useful to be able to clone an object in Javascript, but remove some items.

For instance, if you look at the AST for a Javascript file, the nodes look like this:

{
  "type": "BinaryExpression",
  "operator": "+",
  "left": {
    "type": "BinaryExpression",
    "operator": "+",
    "left": {
      "type": "Literal",
      "value": "Cannot find module '",
      "raw": "\"Cannot find module '\""
    },
    "right": {
      "type": "Identifier",
      "name": "o"
    }
  },
  "right": {
    "type": "Literal",
    "value": "'",
    "raw": "\"'\""
  }
}

If you were trying to track these as you traverse the tree (e.g. using Estraverse) you would want just the root (without the “left” and “right” bits).

Fortunately, there is an easy way to do just that:

tree.push(
  _.omit(
    node, 
    ["left", "right"]
  )
);

Leave a Reply

Your email address will not be published. Required fields are marked *