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

Time:01-09

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.

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

CodePudding user response:

Merging each object inside the array in a main one would be the only solution I can think of. ( I assumed lastName: paris was a typo)

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

const obj = objects.reduce((acc, obj) => Object.assign(acc, obj), {});

const entry_str = Object.entries(obj).map(entry => 
    entry.join('=')
  ).join('&');

console.log(entry_str);

CodePudding user response:

The answer provided by Nina stil uses a nested loop, instead of using forEach, map is used.

For special character handling i strongly recommend to use the URLSearchParams class.

I would advise to join the array of objects in one single objects with reduce and import the entries in a URLSearchParams

const objects = [
    { firstName: "John", lastName: "Doe", age: 46 }, { country: "France", lastName: "Paris" }];
let reduced = objects.reduce((acc, object) => Object.assign(acc, object))
let params = new URLSearchParams(reduced);

console.log(reduced);
console.log(params.toString());

CodePudding user response:

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

  • Related