Retrieve a value from a deeply nested array using “dot” notation

/**
 * retrieve a value from a deeply nested array using "dot" notation
 * 
 * @param String path 
 * @param Object object 
 */
const getValueFromNestedArray = (path, object) => {
    return path.split('.').reduce( (accumulator, currentValue) => {
        return (accumulator && accumulator[currentValue]) ? accumulator[currentValue] : null
    }, object )
}

// test
console.log(getValueFromNestedArray('data.0.a', {
	code: 'code',
    data: [
        {
            a: "111"
        }
    ]
}))

Leave a Reply