简体   繁体   中英

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"

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM