0

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.

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.