Use the following function to retrieve the value of a property nested within another property in JavaScript...
export function retriveValueFromNestedProperty(objectToIterate: any, propertyName: string): any {
var array: Array<string> = propertyName.split(".");
var currentValue: any = objectToIterate[array[0]];
for (var i = 1; i < array.length; i++) {
currentValue = currentValue[array[i]];
}
return currentValue;
}
or simply use the native reduce function!
ReplyDeletevar objectToIterate = {
prop1: {
prop2: {
prop3: 'value'
}
}
}
var propertyName = 'prop1.prop2.prop3';
var value = propertyName.split('.').reduce(function (value, current) {
return value[current];
}, objectToIterate);
console.log(value); // 'value'
Works a treat. Thanks Ryan
Delete