json-change-order
v0.1.0
Published
Create and apply JSON-serializable change orders.
Downloads
186
Maintainers
Readme
JSON Change Order
A dependency-free TypeScript library for creating and applying compact, JSON-serializable transformation instructions.
Install
npm install
npm run buildCreate And Apply
import {
applyChangeOrder,
createChangeOrder,
} from "json-change-order";
const original = {
name: "Ada",
obsolete: true,
roles: ["admin"],
};
const updated = {
name: "Grace",
roles: ["admin", "author"],
};
const order = createChangeOrder(original, updated);
const result = applyChangeOrder(original, order);
// result deeply equals updatedBoth functions are immutable: results do not share nested objects or arrays with either input.
Object Changes
Direct properties create or update values:
{
"name": "Grace",
"created": true
}Object changes recurse. Arrays, primitives, and null replace their current
value.
Delete a property:
{
"obsolete": {
"action": "delete"
}
}Conditionally replace a value:
{
"name": {
"action": "replace",
"old_value": "Ada",
"new_value": "Grace"
}
}Use set to store an object literally when it resembles an instruction:
{
"data": {
"action": "set",
"value": {
"action": "delete"
}
}
}Array Changes
Add one or several values:
{ "action": "append", "value": "last" }{ "action": "prepend", "values": ["first", "second"] }Update attributes on all matching object items:
{
"action": "update",
"value": {
"name": "New",
"description": "Updated item"
},
"where": {
"code": 123
}
}Other selector-based actions:
{ "action": "remove", "where": { "code": 123 } }{
"action": "insert_before",
"value": { "code": 100 },
"where": { "code": 123 }
}{
"action": "insert_after",
"value": { "code": 200 },
"where": { "code": 123 }
}{
"action": "replace_where",
"value": { "code": 123, "name": "Replacement" },
"where": { "code": 123 }
}where is a partial object match using deep JSON equality. Manually written
selector actions affect every matching object.
createChangeOrder uses compact array actions only when it can prove the
generated selector is unique. It falls back to exact replace instructions
for ambiguous transformations.
Development
npm test
npm run check