Skip to content

Instantly share code, notes, and snippets.

@nltesown
Last active February 28, 2020 12:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nltesown/c5e00a500fe40860f2152feb56d78544 to your computer and use it in GitHub Desktop.
Save nltesown/c5e00a500fe40860f2152feb56d78544 to your computer and use it in GitHub Desktop.
A collection (WIP) of useful lodash expressions

Useful lodash expressions

Object: group properties by a given key prefix

Problem: given an object where some properties have keys starting with an arbitrary prefix, we want to transform it so that the corresponding properties are grouped under a prefix-key, and the original keys are renamed to drop the prefix.

Use case: js2xmlparser transforms JSON to XML. Object properties under a @ key (by default) are output as XML attributes.

Source (data):

{
  "@id": 144,
  "@pk": 111,
  "title": "Robino",
  "@year": 1971
}

Target:

{
  "@":
  {
    "pk": 111,
    "id": 144,
    "year": 1971
  },
  "title": "Robino"
}

Expression:

_(data).reduce(
  (acc, v, k, obj) =>
    _.startsWith(k, "@")
      ? _.assign(acc, {
          "@": _.assign(
            acc["@"],
            _(obj)
              .pick(k)
              .mapKeys((v, k) => _.tail(k).join(""))
              .value()
          )
        })
      : _.assign(acc, _.pick(obj, k)),
  {}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment