there is a line:

var q = 'user.name.firstname=Bob&user.name.lastname=Smith&user.favoritecolor=Light%20Blue' 

you need to make such an object out of it

 { 'user': { 'name': { 'firstname': 'Bob', 'lastname': 'Smith' }, 'favoritecolor': 'Light Blue' } } 

stuck on adding nested objects, here is an example of my code

 function convertQueryToMap(query) { var tmp = {}; query = query.replace(/\./ig, ':'); query = query.replace(/\=/ig, ':'); query = query.replace(/\%20/ig, ' '); var arr = query.split('&'); for (var i = 0; i < arr.length; i++){ var elem = arr[i].split(':'); for (var j = 0; j < elem.length; j++){ if(tmp[elem[j]] == undefined){ tmp[elem[j]] = {}; } } } return tmp; } 

    3 answers 3

     var q = 'user.name.firstname=Bob&user.name.lastname=Smith&user.favoritecolor=Light%20Blue'; /*{ 'user': { 'name': { 'firstname': 'Bob', 'lastname': 'Smith' }, 'favoritecolor': 'Light Blue' } }*/ function convertQueryToMap(query) { var tmp = {}, tmp1; query = query.replace(/\./ig, ':'); query = query.replace(/\=/ig, ':'); query = query.replace(/\%20/ig, ' '); var arr = query.split('&'); for (var i = 0; i < arr.length; i++){ var elem = arr[i].split(':'); tmp1 = tmp; for (var j = 0; j < elem.length - 2; j++){ if(tmp1[elem[j]] == undefined){ tmp1[elem[j]] = {}; } tmp1 = tmp1[elem[j]]; } tmp1[elem[j]] = elem[j+1]; } return tmp; } var res = convertQueryToMap(q); console.log(res); 

    • thank! could not catch an hour ... - lesha310392
    • .replace(/\%20/ig, ' ') is a masterpiece! - user207618
    • @Other glad you liked it - Igor
    • I'm waiting for the second part, where it will be: .replace(/\%20/ig, ' ').replace(/\%0A/ig, "\n")... :) - user207618

    We use the transfer on the link:

     let q = 'user.name.firstname=Bob&user.name.lastname=Smith&user.favoritecolor=Light%20Blue', data = {}; // Каждую запись "Ключ=Значение" q.split('&').forEach(part => { let [path, value] = part.split('='); // Ключ и значение let pointer = data; // Указываем на корень объекта path.split('.').forEach((part, i, arr) => { // Делим по точке (кусочки пути) // Если очередной части пути ещё не находится в базе if(!pointer[part]) // То добавляем либо новый объект, либо значение, если это последняя часть pointer[part] = i === arr.length - 1 ? decodeURIComponent(value) : {}; // Смещаем указатель на новый объект. Или на значение, но это не важно тогда pointer = pointer[part]; }); }); console.info(data); 

    • decodeURIComponent like for both parts should be applied, not? - Qwertiy
    • @Qwertiy maybe. True, I do not consider it necessary, the keys - a special thing. - user207618
    • I also made an answer here :) - Qwertiy

     var s = 'user.name.firstname=Bob&user.name.lastname=Smith&user.favoritecolor=Light%20Blue'; var res = {}; s.replace(/([^=&]+|(?==))(=?)([^&]*)/g, function (m, key, eq, val) { var path = decodeURIComponent(key).split("."); key = path.pop(); val = eq ? decodeURIComponent(val) : true; var obj = res; for (var q=0; q<path.length; ++q) { obj = obj[path[q]] = obj[path[q]] || {}; } obj[key] = val; }); console.log(res); 

    • Congratulations :) Oh, I feel that there are no regulars in this parser ... - user207618
    • @Other, why not need? So less code to write than two nested splits :) - Qwertiy
    • Okay, okay, maybe it is, that's why I added it. But I think that it is better to sink for an extra ms, than to write code that you need to go into for a long time. Regularly figs understand what and why without a thoughtful analysis. - user207618
    • By the way, can golf? :) Not the best option, but on the golf course and this is golf. - user207618
    • @Other, actually, I suspect that the regular season is slower than 2 splits. In my opinion, this code is simpler :) And golf - well, you can - there is something to pile up)) Let's call Nicholas, he had thoughts) - Qwertiy