Reputation: 1721
WhY this notation does not work
const result1 = _model['dataarray[0]'];
_model.dataarray
exists and it is an array with 2 elements
this "console.log(_model.dataarray[0])" works fines
Upvotes: 2
Views: 107
Reputation: 32145
Well console.log(_model.dataarray[0])
works fine because _model.dataarray[0]
is different from _model['dataarray[0]']
which is incorrect, you shouldn't wrap the array index in the string.
Use the following syntax:
const result1 = _model['dataarray'][0];
Or like in the console.log()
:
const result1 = _model.dataarray[0];
Edit:
To have a function that dynamically gets a value from an object whther this value is a key
or not, this how could be your code:
getValue = function(_model, valueToFind){
if(_model.hasOwnProperty(valueToFind)){
return _model[valueToFind];
}else if(valueToFind.indexOf("[")>0){
let key = valueToFind.substring(0, valueToFind.indexOf("["));
let index = parseInt(valueToFind.charAt(parseInt(valueToFind.indexOf("["))+1));
return _model[key][index];
}else{
console.log('Please input a valid key!!');
}
}
Demo:
getValue = function(_model, valueToFind){
if(_model.hasOwnProperty(valueToFind)){
return _model[valueToFind];
}else if(valueToFind.indexOf("[")>0){
let key = valueToFind.substring(0, valueToFind.indexOf("["));
let index = parseInt(valueToFind.substring(valueToFind.indexOf("[")+1, valueToFind.indexOf("]")));
console.log(index);
return _model[key][index];
}else{
console.log('Please input a valid key!!');
}
}
var _model = {dataarray: ["test1", "test2"]};
console.log(getValue(_model, "dataarray"));
console.log(getValue(_model, "dataarray[1]"));
console.log(getValue(_model, "property"));
Note:
This function takes only expressions like dataarray[1]
or simple properties, you need to improve it to accept more complex expressions, I just wrote it to give you some hints on how to go with it.
Upvotes: 2
Reputation: 121998
It doesn't work because you wrapped the whole thing as a string and that is not the correct way of accessing a object properties. But only the key should be in string. Otherwise, the interpreter looks for a key called dataarray[0]
which doesn't exist.
Correct syntax is
const result1 = _model['dataarray'][0];
Upvotes: 3