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"]
  )
);

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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