Convert JavaScript string in dot notation into an object reference

前端 未结 27 3098
梦如初夏
梦如初夏 2020-11-21 05:09

Given a JS object

var obj = { a: { b: \'1\', c: \'2\' } }

and a string

\"a.b\"

how can I convert the stri

27条回答
  •  醉梦人生
    2020-11-21 05:35

    It's not clear what your question is. Given your object, obj.a.b would give you "2" just as it is. If you wanted to manipulate the string to use brackets, you could do this:

    var s = 'a.b';
    s = 'obj["' + s.replace(/\./g, '"]["') + '"]';
    alert(s); // displays obj["a"]["b"]
    

提交回复
热议问题