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 ... make me use multiple 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 values in this dictionary are {String}
bad if the reference is greater than the stipulated in the search function ends up returning {Object}
.
Is there a cleaner, more concise way to search for 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><buttonclass="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>