Create nested object from query string in Javascript

落花浮王杯 提交于 2020-07-09 13:08:51

问题


I have the following query string:

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

How to convert to nested object like this:

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

I have tried the following code but something is wrong:

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;
}

Do you know a solution?


回答1:


You can use reduce method to create nested structure and split method to split the query first on parts based on & and also to get key and value from each part.

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)



回答2:


You could decode the string, split for parts, then for keys and value and assign the value to the nested object.

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; }


来源:https://stackoverflow.com/questions/58355738/create-nested-object-from-query-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!