I have the following goal. An array of strings that I can use to get the keys of an object that I need. My problem is, I don’t know how to get to the nested properties in my loop.
My array:
JavaScript
x
2
1
const arr = ["firstName", "age", "organization.name"]
2
My object:
JavaScript
1
2
1
const obj = {id: 1, firstName: "John", lastName: "Smith", age: 20, organization: {id: 40, name: "Contoso"}}
2
My loop:
JavaScript
1
2
1
for(let i = 0; i < arr.length; i++){ console.log(obj[arr[i]) }
2
Of course, all nested properties don’t work. But how can I access them within a loop?
I tried it with arr[i].split(".")
but don’t know, how I can put an array of keys to get the properties. This works but isn’t good for deeply nested properties.
JavaScript
1
3
1
const splited = arr[i].split(".");
2
console.log(obj[splited[0][splited[1]);
3
I probably have the wrong approach, but can’t come up with the right answer.
Advertisement
Answer
Here is a solution for you
JavaScript
1
7
1
function getValue(o, k) {
2
return k.split('.').reduce((r, e) => {
3
if (!r) return r;
4
else return r[e] || undefined;
5
}, o);
6
}
7
Here is usage
JavaScript
1
2
1
console.log(arr.map(row => getValue(obj, row)));
2
Here is result
JavaScript
1
2
1
["John", 20, "Contoso"]
2