npm package: @nolwenture/json-modifier
Description: Dynamic JSON manipulator
Author: Antti Vikman
Latest version: 1.1.0

# json-modifier

Dynamic JSON manipulator

## Installation

With npm:

```text
npm install @nolwenture/json-modifier
```

With yarn:

```text
yarn add @nolwenture/json-modifier
```

## Usage

### Basic usage

Json-modifier can be used to map values from one JSON object to another. During the mapping, the values can be modified in various ways, for example by executing calculations on numeric values or by joining strings.

ModifyJson function gets three parameters:
|Parameter | Description|
|----------|------------|
|entity | an object that has the original values|
|map| an object that has the structure of the desired object|
|options| an optional object, see structure below|

Options
|Parameter | Description|
|----------|------------|
|returnNew| an optional boolean value that determines whether the outcome will be returned as a new object|.
|functions | an object that allows defining custom functions, see example in "Custom functions" |

```ts
import { modifyJson } from "@nolwenture/json-modifier";

const entity = {
  name: "A name",
  total: {
    amount: 1234560,
    currency: { divisor: 10, symbol: "$" },
  },
  items: {
    array: [
      {
        item: {
          name: "Item B",
        },
        value: 12300,
        currencyId: "EUR",
        currency: {
          divisor: 100,
        },
      },
      {
        item: {
          name: "Item C",
        },
        value: 34500,
        currencyId: "USD",
        currency: {
          divisor: 100,
        },
      },
    ],
  },
};

const map = {
  Name: "name",
  Amount: {
    $calc: [{ $ref: "total.amount" }, "/", { $ref: "total.currency.divisor" }],
  },
  Currency: "total.currency.symbol",
  Items: {
    "$array.join": [
      {
        "$array.formatToStrings": [
          {
            "$array.map": [
              { $ref: "items.array" },
              {
                decimalValue: {
                  $calc: [{ $ref: "value" }, "/", { $ref: "currency.divisor" }],
                },
              },
              { returnNew: false },
            ],
          },
          "${item.name} ${decimalValue} ${currencyId}",
        ],
      },
      "; ",
    ],
  },
  TotalItems: {
    $if: [
      {
        $eq: [
          { "$array.length": [{ $ref: "items.array" }] },
          { $fixedValue: 2 },
        ],
      },
      {
        $calc: [
          { "$array.length": [{ $ref: "items.array" }] },
          CalcOperators.ADDITION,
          { $fixedValue: 1 },
        ],
      },
      { "$array.length": [{ $ref: "items.array" }] },
    ],
  },
};

const output = modifyJson(entity, map, { returnNew: true });

/* Output:
{
  Name: 'A name',
  Amount: 123456,
  Currency: '$',
  Items: 'Item B 123 EUR; Item C 345 USD',
};
*/
```

### Available functions

Available functions are determined by the type of the original JSON object property.

| Type      | Functions                                                                   |
| --------- | --------------------------------------------------------------------------- |
| string    | append                                                                      |
| number    | add, subtract, multiply, divide                                             |
| boolean   |                                                                             |
| array     | append, prepend                                                             |
| object    | append                                                                      |
| undefined | calc, array.join, array.pick, array.filter, array.map, array.formatToString |

If a property doesn't exist in the original object, you can create a new property to the target object using functions mentioned on the table above for the undefined type.

### Custom functions

It is possible to extend above list of functions with custom implementations when such need arises.

```ts
const original = {
  startDate: new Date("2024-01-01"),
  endDate: new Date("2024-02-29"),
};
const modifiers = {
  dateDiff: { "$date.diff": [{ $ref: "startDate" }, { $ref: "endDate" }] },
};
const result = modifyJson(original, modifiers, {
  functions: {
    undefined: {
      "date.diff": (_, params, ref, rootRef) => {
        const [startDate, endDate] = solveParams(
          params,
          ref,
          rootRef
        ) as unknown as [Date, Date];
        const diffTime = Math.abs(endDate.valueOf() - startDate.valueOf());
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return diffDays;
      },
    },
  },
});
```