Skip to content
Advertisement

Get Values of nested Objects in Loop

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:

const arr = ["firstName", "age", "organization.name"]

My object:

const obj = {id: 1, firstName: "John", lastName: "Smith", age: 20, organization: {id: 40, name: "Contoso"}}

My loop:

for(let i = 0; i < arr.length; i++){ console.log(obj[arr[i]) }

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.

const splited = arr[i].split(".");
console.log(obj[splited[0][splited[1]);

I probably have the wrong approach, but can’t come up with the right answer.

Advertisement

Answer

Here is a solution for you

function getValue(o, k) {
  return k.split('.').reduce((r, e) => {
    if (!r) return r;
    else return r[e] || undefined;
  }, o);
}

Here is usage

console.log(arr.map(row => getValue(obj, row)));

Here is result

["John", 20, "Contoso"]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement