Get object with string identifier

前端 未结 4 1668
轮回少年
轮回少年 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 05:47

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

提交回复
热议问题