How to turn dot notation string into an object in Javascript

后端 未结 2 1045
情书的邮戳
情书的邮戳 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);

    0 讨论(0)
  • 2021-01-06 17:53

    You could split the given key strings and save the last key for the assignment of the value after iterating the keys to the nested property.

    var data = [{ 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' }],
        result = data.reduce(function (r, o) {
            var path = o.key.split('.'),
                last = path.pop();
    
            path.reduce(function (p, k) {
                return p[k] = p[k] || {};
            }, r)[last] = o.value;
            return r;
        }, {});
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题