How do I create such a URL based on an object?

  • 0
    There is an object
    {
       "FName": "Sergey",
       "LName": "Ivanov",
       "Email": "[email protected]",
       "Phone": "+375296666666",
       "Sex": "Male",
       "Skills": ["HTML", "CSS", "JavaScript"],
      "Department": ["FrontEnd", "SalesForce"]
    }


    how to generate such url:

    ... / index.html? FName = Sergey & amp; LName = Ivanov & amp; [email protected]& Phone = + 375296666666 & amp; Sex = Male & amp; Skills = HTML | CSS | JavaScript & amp; Department = FrontEnd | SalesForce
    JavaScript Anonymous, Nov 9, 2020

  • 2 Answers
  • 0
    Option and interactive

    const obj = {
    "FName": "Sergey",
    "LName": "Ivanov",
    "Email": "[email protected]",
    "Phone": "+375296666666",
    "Sex": "Male",
    "Skills": ["HTML", "CSS", "JavaScript"],
    "Department": ["FrontEnd", "SalesForce"]
    };

    const str = Object.keys(obj)
    .map(key => [key, obj[key]])
    .map(([key, val]) => [key, Array.isArray(val) ? val.join('|') : val])
    .map(([key, val]) => key.concat('=').concat(val))
    .join('&');

    console.log('?' + str);




    P.S.

    it would be nice to add encodeURI or encodeURIComponent



    something like this

    console.log (`? $ {encodeURI (str)}`);
    Anonymous

  • 0
    const obj = {
    "FName": "Sergey",
    "LName": "Ivanov",
    "Email": "[email protected]",
    "Phone": "+375296666666",
    "Sex": "Male",
    "Skills": ["HTML", "CSS", "JavaScript"],
    "Department": ["FrontEnd", "SalesForce"]
    }

    const params = new URLSearchParams(obj)

    console.log(params.toString()) // FName=Sergey&LName=Ivanov&Email=s-ivanow%40gmail.com&Phone=%2B375296666666&Sex=Male&Skills=HTML%2CCSS%2CJavaScript&Department=FrontEnd%2CSalesForce
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!