2021年6月25日 星期五

[enumerate, object type, typescript] How to enumerate the properties of an object and access the values

How to enumerate the properties of a TypeScript object and access the values

井民全, Jing, mqjing@gmail.com


GitHub: (view)

Quick

interface Status {

    id: number;

    msg: string;

}


let mystatus:Status = {id: 123, msg:'this is the msg'};

for (var prop in mystatus) {

       if (mystatus.hasOwnProperty(prop)) {

           console.log('prop = ' + prop + ', value = ' + mystatus[prop as keyof Status]);

       }

    }

}


Code


interface Status {

    id: number;

    msg: string;

}



function enumObj(){

    let mystatus:Status = {id: 123, msg:'this is the msg'};

    for (var key in mystatus) {

        if (mystatus.hasOwnProperty(key)) {

            console.log('key = ' + key + ', value = ' + mystatus[key as keyof Status]);

        }

    }

}


function getParamUrl(para:Status):string{

    var url = '?';

    let bFirst = false;


    for (var key in para) {

        if (para.hasOwnProperty(key)) {

            url += (bFirst ? '&' : '') + key + "=" + para[key as keyof Status];

        }

        bFirst = true;

    }


    return url;

}


function main(){

    enumObj();


    let statusPara:Status = {id: 123, msg:'this is the msg'};

    let url = getParamUrl(statusPara);

    console.log('url = ' + url);

}

main();




Result

Reference

  1. How do I loop through or enumerate a JavaScript object?, https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object