Convert javascript dot notation object to nested object

后端 未结 7 1285
我在风中等你
我在风中等你 2020-11-28 09:54

I\'m trying to build a function that would expand an object like :

{
    \'ab.cd.e\' : \'foo\',
    \'ab.cd.f\' : \'bar\',
    \'ab.g\' : \'foo2\'
}
<         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 10:46

    If you're using Node.js (e.g. - if not cut and paste out of our module), try this package: https://www.npmjs.org/package/dataobject-parser

    Built a module that does the forward/reverse operations:

    https://github.com/Gigzolo/dataobject-parser

    It's designed as a self managed object right now. Used by instantiating an instance of DataObjectParser.

    var structured = DataObjectParser.transpose({
        'ab.cd.e' : 'foo',
        'ab.cd.f' : 'bar',
        'ab.g' : 'foo2'
    });                                                                                                                                                                                                                                                                                                                                                                                                                                                   
    

    structured.data() returns your nested object:

    {ab: {cd: {e:'foo', f:'bar'}, g:'foo2'}}

    So here's a working example in JSFiddle:

    http://jsfiddle.net/H8Cqx/

提交回复
热议问题