javascript – Fetch values ​​in an object

Question:

I'm trying to access properties of an object, a dictionary.

However the references are in {String} format and their concatenation through dot ( . ) and I'm using split() to break this {String} into an array… but this ends up making me use several if|else in the function of search.

let base = {} // o dicionário
let str = 'indice.subindice.chave' // a referencia
//
let m = str.split('.') // a matriz de consulta
//
return base[m[0]][m[1]][m[2]][m[3]]

Basically all the values ​​in this dictionary are {String} but if the reference is greater than what is stipulated in the search function it ends up returning an {Object} .

Is there a cleaner and more concise way to fetch these values ​​by reference?

example :

let base = {
    misc: {
       first: 'look',
       level: {
          move: 'handler'
       }
    },
    words: {
       page: {
          index: {
             nav: 'rule',
             aside: {
                bottom: 'awesome'
             }
          }
       }
    }
}

function getWord(list) {
    //
    try {
        let array = list.split('.');
        if ( Array.isArray(array) && array.length > 0 ) {
            if ( array[3] ) {
                return base[array[0]][array[1]][array[2]][array[3]];
            } else if ( array[2] ) {
               return base[array[0]][array[1]][array[2]];
            } else {
               return base[array[0]][array[1]];
            }
        } else {
            return false;
        }
    } catch(ex) {
        return false;
    }
}

$('.btn ').on('click', function(evt) {
    let word = $(this).attr('data')
    console.log(getWord(word))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button class="btn" data="misc.first">nível 1</button>

<button class="btn" data="misc.level.move">nível 2</button>

<button class="btn" data="words.page.index.nav">nível 3</button>

<button class="btn" data="words.page.index.aside.bottom">nível 4</button>

Answer:

Yes, using the reduce function

const base = {
    misc: {
       first: 'look',
       level: {
          move: 'handler'
       }
    },
    words: {
       page: {
          index: {
             nav: 'rule',
             aside: {
                bottom: 'awesome'
             }
          }
       }
    }
}

$('.btn ').on('click', function(evt) {
    const word = $(this).attr('data');
    console.log(getWord(word));
})

function getWord(list) {
    return list.split('.').reduce((o,i) => o[i], base);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn" data="misc.first">nível 1</button>
<button class="btn" data="misc.level.move">nível 2</button>
<button class="btn" data="words.page.index.nav">nível 3</button>
<button class="btn" data="words.page.index.aside.bottom">nível 4</button>
Scroll to Top