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

If you want a good Javascript book, I got a lot out of Secrets of the Javascript Ninja.

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 *