Get object with string identifier

前端 未结 4 1664
轮回少年
轮回少年 2021-01-29 04:58

I need help with getting property of object with String in JS.

I have object

elements = {
    element : {
            date: {
                 day: \'Mo         


        
4条回答
  •  时光说笑
    2021-01-29 06:05

    You can do something like this :

    var elements = {
        element : {
                date: {
                     day: 'Monday'
                }
        },
        cars : {
            racing : "Lamborghini",
            classic: "Rolls Royce"  
        }
    }
    
    
    function getObjectByStringIdentifier ( stringId ) {
        objects = stringId.split(".");
        element = elements; 
        for(i=0; i < objects.length; i++)
            element = element[objects[i]]; 
        return element;
    }
    
    alert(getObjectByStringIdentifier("cars.racing"));
    alert(getObjectByStringIdentifier("element.date.day"));
    alert(getObjectByStringIdentifier("cars.classic"));

提交回复
热议问题