Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I turn an array of JavaScript objects into an URL string with only one loop?

I am trying to turn an array of JavaScript objects into a URL string with params, as seen below:

const objects = [{
    firstName: "John",
    lastName: "Doe",
    age: 46
  },
  {
    country: "France",
    lastName: "Paris"
  }
]

let entry_arr = [];

objects.forEach(obj => {
  Object.entries(obj).forEach(entry => {
    entry_arr.push(entry.join('='));
  });
});

let entry_str = entry_arr.join('&');

console.log(entry_str);

By all appearances, the above code works. There is a problem though.

The problem

As you can see, I have 2 nested forEach loops. For better performance, I wish I knew how to avoid this nesting and instead use only one forEach loop.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I achieve the same result with inly one loop?

>Solution :

At least, you need to map the entries with joining key and value and join the nested entries and outer array.

const
    objects = [{ firstName: "John", lastName: "Doe", age: 46 }, { country: "France", lastName: "Paris" }],
    result = objects
        .map(object => Object
            .entries(object)
            .map(entry => entry.join('='))
            .join('&')
        )
        .join('&');

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading