4
I’m trying to access properties of an object, a dictionary.
However the references are in format {String}
and its concatenation through a point (.) and I’m using split()
to break this {String}
in a matrix... but this ends up making me use several if|else
in the search function.
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 of this dictionary are {String}
but if the reference is greater than the stipulated in the search function ends up returning a {Object}
.
Is there any cleaner and more concise way to search 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>
That was really succinct... thank you.
– Lauro Moraes