Get object with string identifier

a 夏天 提交于 2020-01-22 02:40:08

问题


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

I have object

elements = {
    element : {
            date: {
                 day: 'Monday'
            }
    }
}

and i have JS function where input is "element.date.day". And basically i need to do something like this:

function getObjectByStringIdentifier ( stringId ) {
    return elements[stringId];
}

is this possible in JS ?


回答1:


You can do something like this

var elements = {
  element: {
    date: {
      day: 'Monday'
    },
    example: {
      abc: 'hii'
    }
  }
};

function getObjectByStringIdentifier(stringId) {
  stringId = stringId.split('.');
  // split string using `.`
  var res = elements;
  // define res as object
  for (var i = 0; i < stringId.length; i++)
  // iterate over array
    res = res[stringId[i]]
    // update res as inner object value
  return res;
  // return result
}

console.log(getObjectByStringIdentifier("element.date.day"));
console.log(getObjectByStringIdentifier("element.example.abc"));



回答2:


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"));



回答3:


Yes you can ! :-)

var elements = {
    element : {
            date: {
                 day: 'Monday'
            }
    }
}

function getObjectByStringIdentifier ( stringId ) {
    
    //return elements[stringId];
    //            ^      ^  
    //            |      |  
    //            |------|---------------------------------------------|  
    //                   |                                             |
    //        -----------|                                             | 
    //        |                                                        |
    //        °                                                        °
    return stringId.split('.').reduce(function(t,v){return t[v]; } , elements)
}


/** let's test it now ! **/

var stringIdentifier = "element.date.day";
var result = getObjectByStringIdentifier( stringIdentifier );


document.getElementById('el').innerHTML = result;
<div id='el'></div>



回答4:


Modern browsers support JSON.parse().

var arr_from_json = JSON.parse( json_string );

In browsers that don't, you can include the json2 library.

alert(arr_from_json.elements);


来源:https://stackoverflow.com/questions/33075475/get-object-with-string-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!