2

I am building some forms that need to handle entities that might have nested objects. So I need the interface to accept as the field key either a string or an array of strings with each piece of the path to the value (like the example below).

const obj = {
    name: "John",
    role: {
        id: 1,
        name: "admin"
    }
}

const key1 = 'name'
const key2 = ['role', 'name']

function getValueByKey (key, obj) {

    if (Array.isArray(key)) {
        //Get value if key is array.
    } else {

        return obj[key]
    }
}

console.log(getValueByKey(key1, obj))
//Should output "John"
console.log(getValueByKey(key2, obj))
//Should output "admin"

2 Answers 2

1

You could take a recursive approach by using the key at index zero for handing over a nested property of the given object.

function getValueByKey(key, obj) {
    return Array.isArray(key) && key.length > 1
        ? getValueByKey(key.slice(1), obj[key[0]])
        : obj[key];
}

const
    obj = { name: "John", role: { id: 1, name: "admin" } },
    key1 = 'name',
    key2 = ['role', 'name'];

console.log(getValueByKey(key1, obj)); // "John"
console.log(getValueByKey(key2, obj)); // "admin"

An iterative approach

function getValueByKey(key, obj) {
    return [].concat(key).reduce((o, k) => o[k], obj);
}

const
    obj = { name: "John", role: { id: 1, name: "admin" } },
    key1 = 'name',
    key2 = ['role', 'name'];

console.log(getValueByKey(key1, obj)); // "John"
console.log(getValueByKey(key2, obj)); // "admin"

Sign up to request clarification or add additional context in comments.

Comments

1

Use Lodash's get method. It does exactly what you want.

https://lodash.com/docs/#get

_.get(obj, 'name');
// => John
 
_.get(obj, "role.name");
// => admin

If you're unable to use lodash directly, you can always look at its implementation here; it is as tried-and-tested as it gets.

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.