npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mappingutils

v2.0.2

Published

Lightweight JSON transformation utility.

Downloads

595

Readme

mappingutils

Lightweight JSON transformation utility.

Table of Contents

Prerequisites

If using Node.js ensure your version is v18 or higher.

Installation

You can install mappingutils directly from npm: npm install mappingutils

Setup

Node.js

cjs

let { mapObj } = require("mappingutils");
...

esm

import { mapObj } from "mappingutils";
...

Browser

esm (bundlers) If you're using a bundler (e.g Vite), you could use the ESM import statement.

import { mapObj } from "mappingutils";
...

cdn Or you could use cdn for importing the minified version of the package.

<script src="https://cdn.jsdelivr.net/npm/mappingutils@latest/dist/index.min.js"></script>
<script>
 ...
</script>

Basic Usage

It uses JSONPath syntax for selecting the values from the input and a similar syntax for the output.

let { mapObj } = require("mappingutils");

let source = {
  event: {
    agency: "MI6",
    data: {
      name: "James",
      lname: "Bond",
      id: "007",
    },
  },
};

let mapping = {
  "$.code": "$.event.data.id",
  "$.private.agency": "$.event.agency",
  "$.private.agent": [
      "$.event.data.name",
      "$.event.data.lname",
      (a, b) => `${a} ${b}`.toUpperCase(),
  ],
};

let output = mapObj(source, mapping);
console.log(output);

It will print out

[
  {
    code: "007",
    private: {
      agency: "MI6",
      agent: "JAMES BOND",
    }
  }
]

Use Cases

Here are some practical scenarios where mappingutils can be useful:

  • API Data Transformation: Easily map and structure incoming JSON data from external APIs into a desired format for internal use.
  • Data Cleaning: Use the provided transformation functions to clean and standardize data (e.g., trimming whitespace, converting case).
  • Data Aggregation: Group or merge similar objects into a single structure for simplified data processing or reporting.

Functions

addProp(obj, key, value)

Add a key property to the object obj with the value value. Returns a deep copy of the object with the new property added.

  • Example:
import { addProp } from "mappingutils";

let obj = {
  name: "Alice",
  age: 30,
};

let updatedObj = addProp(obj, "$.address.city", "Wonderland");
console.log(updatedObj);

Prints out

{
  name: "Alice",
  age: 30,
  address: {
    city: "Wonderland"
  }
}

mergeObjArr(objArr, prop)

Merges the prop array values of the object objArr. Returns a deep copy of the first object in the array, with the prop array values concatenated.

  • Example:
import { mergeObjArr } from "mappingutils";

let objArr = [
  { tx_number: 1111, tx_date: "2024-10-26", items: [{ item: "9991" }] },
  { tx_number: 1112, tx_date: "2024-10-26", items: [{ item: "9992" }, { item: "9993" }], },
  { tx_number: 1113, tx_date: "2024-10-26", items: [{ item: "9994" }] },
];

let prop = "$.items[]";

let mergedObj = mergeObjArr(objArr, prop);
console.log(mergedObj);

Prints out

{
  tx_number: 1111,
  tx_date: '2024-10-26',
  items: [
    { item: '9991' },
    { item: '9992' },
    { item: '9993' },
    { item: '9994' }
  ]
}

mapObj(source, mappings)

Transforms the source object based on the provided mapping transformation, where a mapping is an object with from, to, and an optional property fn to apply to the from value. Each mapping object's key-value pair should use JSONPath syntax:

  • The key represents the target field path in the transformed object.
  • The value represents the source field path(s) in the source object.
  • If a single source field is required, the value should be a JSONPath string pointing to that field.
  • If multiple source fields are required, provide an array where:
  • Each element before the last is a JSONPath string pointing to a source field.
  • The last element is a function that takes the resolved source values as arguments and computes the target field value.

Returns an array of transformed objects, with fields derived from applying the mapping to the source object.

  • Example:
import { mapObj } from "mappingutils";

let source = {
  event: {
    agency: "MI6",
    data: {
      name: "James",
      lastName: "Bond",
      id: "007",
    },
    location: {
      country: "UK",
      city: "London",
    },
  },
  attendees: [
    { name: "M", role: "Director" },
    { name: "Q", role: "Tech Expert" },
  ],
};

let mapping = {
  "$.agency": "$.event.agency",
  "$.location": [
    "$.event.location.city",
    "$.event.location.country",
    (a, b) => a.toUpperCase() + "/" + b,
  ],
  "$.attendees": "$.attendees",
};

let output = mapObj(source, mapping);
console.log(JSON.stringify(output, null, 2));

Prints out

[
  {
    "agency": "MI6",
    "location": "LONDON/UK",
    "attendees": [
      {
        "name": "M",
        "role": "Director"
      },
      {
        "name": "Q",
        "role": "Tech Expert"
      }
    ]
  }
]

mapObjArr(source, mappings)

Transforms each object in the source array based on the provided mapping transformation. The mapping object should follow the same conventions as in the mapObj function.

  • Example:
import { mapObjArr } from "mappingutils";

let source = [
  {
    id: 1,
    name: "Alice",
    score: 90,
    extra_curricular_activities: ["Trivia and Quiz"],
  },
  {
    id: 2,
    name: "Bob",
    score: 80,
    extra_curricular_activities: ["Robotics Club"],
  },
];

let mapping = {
  "$.name": "$.name",
  "$.grade": ["$.score", (score) => (score >= 85 ? "A" : "B")],
};

let outputArr = mapObjArr(source, mapping);
console.log(JSON.stringify(outputArr, null, 2));

Prints out

[
  {
    "fname": "Alice",
    "grade": "A"
  },
  {
    "fname": "Bob",
    "grade": "B"
  }
]

Running Tests

To ensure that your changes are working as expected, you can run the test suite:

  • npm run test Make sure all tests pass before submitting a pull request.

Issue Reporting

If you encounter any issues or have suggestions for improvements, please open an issue in the GitHub repository. To help us address your concerns more effectively, please use the following template:

Issue Template

Title: [Short description of the issue]

Description: A clear and concise description of what the issue is.

Steps to Reproduce:

  1. [Step one]
  2. [Step two]
  3. [Step three]

Expected Behavior: A clear description of what you expected to happen.

Actual Behavior: A clear description of what actually happened.

Environment:

  • Node.js version: [your Node.js version]
  • Operating System: [your OS]
  • Package version: [version of mappingutils]

Additional Context: Any other context or screenshots about the issue.

Contributing

We welcome contributions! If you find a bug or have a feature request, feel free to create an issue in the GitHub repository.

License

MIT