1.0.0 • Published 4 years ago
deep-reduce-object v1.0.0
deep-reduce-object
Performs a deep reduce on complex nested objects and arrays
Install
npm i deep-reduce-objectconst deepReduce = require('deep-reduce-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 },
]
}
]
}
// Get the sum of all values
const initialValue = 0
const reducer = (a, b) => a + b)
const path = 'transactions.amounts.value'
const sum = deepReduce(complexNestedObject, reducer, initialValue, path)
// sum = 100API
deepReduce takes 5 arguments. 4 mandatory and 1 optional:
deepReduce (
collection: object|array,
reducer: (accumulator: any, currentValue: any) => any,
initialValue: any
path: string,
context: any
): anyArguments
collectionObject or Array to traverse.reducerFunction to call with every value inobj-tree. See section below forreducerfunction signature.initialValueInitial value ofreducedpassed toreducer.pathPath to the inner property of collection to be reduced.context(optional) Bound to reducer asthis.
Arguments for reducer function
The reducer function is called with these arguments:
(accumulator: any, value: any) => anyaccumulatorThe accumulated value returned by the reducervalueValue of current path.
Development
git clone https://github.com/eltonbor/deep-reduce-object.git
cd deep-reduce-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
4 years ago