1.0.0 • Published 3 years ago
deep-transform-object v1.0.0
deep-transform-object
Performs a deep transformation on complex nested objects and arrays
Install
npm i deep-transform-objectconst deepTransform = require('deep-transform-object')
// Complex nested objects
const complexNestedObject = {
transactions: [
{
id: 1,
amounts: [
{ value: 10 },
{ value: 20 },
]
},
{
id: 2,
// amounts: undefined
},
{
id: 3,
amounts: [
{ value: 30 },
{ value: 40 },
]
}
]
}
// Converts all `values` keys to string
const initialValue = 0
const transformer = (val) => String(val))
const path = 'transactions.amounts.value'
const sum = deepTransform(complexNestedObject, transformer, path)
// sum = 100API
deepTransform takes 4 arguments. 3 mandatory and 1 optional:
deepTransform (
collection: object|array,
transformer: (currentValue: any) => any, // MUST RETURN THE TRANSFORMED OBJECT
path: string,
context: any
): anyArguments
collectionObject or Array to traverse.transformerFunction to call with every value inobj-tree. See section below fortransformerfunction signature.pathPath to the inner property of collection to be transformed.context(optional) Bound to transformer asthis.
Arguments for transformer function
The transformer function is called with these arguments:
(value: any) => anyvalueValue of current path.- MUST RETURN THE TRANSFORMED VALUE
Development
git clone https://github.com/eltonbor/deep-transform-object.git
cd deep-transform-object
npm install
npm test # runs node index.test.jsInspired on
https://github.com/kmalakoff/reduce-deep
License
MIT © 2022 Elton Tasca Borssoi
1.0.0
3 years ago