Monday, 11 May 2015

How to retrieve nested property values in JavaScript / Typescript

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;
}

2 comments:

  1. or simply use the native reduce function!

    var 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'

    ReplyDelete

How to by pass the Jaguary X-Type enter security pin screen after changing battery

How to bypass security code on Jaguar X-Type touchscreen Satellite Navigational units. Just hold the skip track, AMEM and PTY buttons ...