根据Javascript中的查询字符串创建嵌套对象

时间:2019-10-12 15:37:41

标签: javascript javascript-objects query-string

我有以下查询字符串:

student.name.firstname=Foo&student.name.lastname=Bar&student.address=My%20Street

如何像这样转换为嵌套对象:

{
  student:{
    name:{
      firstname: "Foo",
      lastname: "Bar"
    },
    address: "My Street"
  }
}

我尝试了以下代码,但是出了点问题:

function convertQueryToMap(query) {
    var params = {};
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        var subpairs;
        if (pair[0].includes('.')) {
            subpairs = pair[0].split('.');
            var object = {};
            subpairs.reduce(function(o, s, i) {
                if (i === subpairs.length-1) {
                    return o[s] = decodeURIComponent(pair[1]);
                } else {
                    return o[s] = {};
                }
            }, object);
        }
    }
    return params;
}

您知道解决方案吗?

2 个答案:

答案 0 :(得分:3)

您可以使用reduce方法来创建嵌套结构,并可以使用split方法来基于&首先对部件进行查询拆分,还可以从每个部件中获取键和值。

const query = 'student.name.firstname=Foo&student.name.lastname=Bar&student.address=My%20Street'

const toObject = string => {
  return string.split('&').reduce((r, s) => {
    const [key, val] = s.split('=');

    key.split('.').reduce((a, e, i, ar) => {
      return a[e] || (a[e] = (ar[i + 1] ? {} : val.replace(/%20/g, ' ')))
    }, r);

    return r;
  }, {})
}

const result = toObject(query);
console.log(result)

答案 1 :(得分:1)

您可以解码字符串,拆分为部分,然后拆分为键和值,然后将值分配给嵌套对象。

function setValue(object, keys, value) {
    var last = keys.pop();
        
    keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}

var string = 'student.name.firstname=Foo&student.name.lastname=Bar&user.address=My%20Street',
    result = {};
    
decodeURI(string).split('&').forEach(s => {
    var [key, value] = s.split('=');
    setValue(result, key.split('.'), value);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }