-1

I have a string as

string = "foo.call=45&doo.foo=20&foo.in=5";

now I need one object obj such that

obj = {"foo": {"call": "45"}} {"foo": {"call": "45","in":"5"},"doo": {"foo":20}}

How can I do this in JavaScript? For one string = "foo.call=45"

function aaa(string){
    var aa = string.split('=')[0],
        bb = string.split('=')[1];
    function setValue(object, path, value) {
    var way = path.split('.'),
        last = way.pop();
    way.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
    return object;
    }
    var object = JSON.stringify(setValue({}, aa, bb));
    console.log(object);    
}
magnum888
  • 23
  • 1
  • 4
  • 1
    This may help with part of your question: [How to set object property (of object property of..) given its string name in JavaScript?](https://stackoverflow.com/questions/13719593/how-to-set-object-property-of-object-property-of-given-its-string-name-in-ja) – Jonathan Lonowski May 19 '18 at 08:45
  • 1
    Welcome to Stack Overflow! Please take the [tour] and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder May 19 '18 at 08:46
  • Possible duplicate of [How to set object property (of object property of..) given its string name in JavaScript?](https://stackoverflow.com/questions/13719593/how-to-set-object-property-of-object-property-of-given-its-string-name-in-ja) – Asons May 19 '18 at 09:01

1 Answers1

1

You could split the string by equal sign and take the left part as path to the value in an object.

function setValue(object, path, value) {
    var way = path.split('.'),
        last = way.pop();

    way.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
    return object;
}

function getObject(string, object = {}) {
    string
        .split('&')
        .forEach(s => setValue(object, ...s.split('=')));

    return object;
}

console.log(getObject('foo.test.rest.call=45'));
console.log(getObject('foo.call=45&doo.foo=20&foo.in=5'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392