Skip to content
Advertisement

Javascript – How to reference object nested values using an array as reference

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"

Advertisement

Answer

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"
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement