UPDATE: While there is good value to the code provided in the answers below, an improved version of this question, and its answer, can be found here.
EDIT: Correcting the sample data object and simplifying (hopefully) the question
GOAL: Given the below object, a function should parse the object through all its nestings and return the values that correspond to the keypath string argument, which might be a simple string, or include bracketed/dotted notation. The solution should work in Angular (plain JavaScript, TypeScript, a library that works in Angular).
My object:
const response = {
"id": "0",
"version": "0.1",
"interests": [ {
"categories": ["baseball", "football"],
"refreshments": {
"drinks": ["beer", "soft drink"],
}
}, {
"categories": ["movies", "books"],
"refreshments": {
"drinks": ["coffee", "tea"]
}
} ],
"goals": [ {
"maxCalories": {
"drinks": "350",
"pizza": "700",
}
} ],
}
The initial function was:
function getValues(name, row) {
return name
.replace(/\]/g, '')
.split('[')
.map(item => item.split('.'))
.reduce((arr, next) => [...arr, ...next], [])
.reduce ((obj, key) => obj && obj[key], row);
}
So, if we run getValues("interests[refreshments][drinks]", response);
the function should return an array with all applicable values: ["beer", "soft drink", "coffee", "tea"].
The above works fine for a simple string key. getRowValue("version", response)
yields "0.1" as expected. But, getRowValue("interests[refreshments][drinks]", response)
returns undefined
.
I crawled through this and the many related links, but am having difficulty understanding how to deal with the complex nature of the object.