I have one array which have all the properties of values for object . something like this.
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
console.log(ab[act[0]]);
how to access value of object using act values?
I have one array which have all the properties of values for object . something like this.
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
console.log(ab[act[0]]);
how to access value of object using act values?
You have to split the string act[0]
as your object does not contain any key named "name.first"
:
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
var key = act[0].split('.');
console.log(ab[key[0]][key[1]]);
try this simple
var ab = {first: 'a',
last: 'b',
age: '24'}
var ac = [];
ac.push(ab);
console.log(ac[0]);
Agree that it isn't natively supported, but you can use a little rectifier function to iterate down the passed path and get the value. This could probably be optimized, but works:
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
function getProperty(inputObj, path) {
var pathArr = path.split('.');
var currentObjLevelOrOutput;
var i;
if (pathArr.length > 1) {
currentObjLevelOrOutput = inputObj;
for (i=0; i < pathArr.length; i++) {
currentObjLevelOrOutput = currentObjLevelOrOutput[pathArr[i]];
}
} else {
currentObjLevelOrOutput = inputObj[path];
}
return currentObjLevelOrOutput;
}
console.log(getProperty(ab,act[0]));