How to turn dot notation string into an object in Javascript

后端 未结 2 1046
情书的邮戳
情书的邮戳 2021-01-06 17:03

I\'m trying to turn a dot notation string into an object, for example given

  [{
      key: \'app.team.instance\',
      value: \'some value1\'
  }, {
               


        
2条回答
  •  一整个雨季
    2021-01-06 17:39

    You can use array.prototype.reduce :

      var datas = [ {key: 'app.team.instance', value: 'some value1'}, {key: 'app.team.server.obj', value: 'some value'}, {key: 'app.team.app.some',value: 'some value'}, {key: 'app.service.awesome.more', value: 'more values'}];
    
    var res = datas.reduce((m, o) => {
        var keys = o.key.split('.');
        var cur = m;
        keys.forEach((key, i) => { 
            if (i < keys.length - 1) {
                cur[key] = cur[key] || {};
                cur = cur[key];
            } else {
                cur[key] = o.value;
            }
        });
        return m;
    }, {});
    
    console.log(res);

提交回复
热议问题