如何将JavaScript对象数组转换为只使用一个循环的URL字符串?

huangapple go评论69阅读模式
英文:

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

问题

我正在尝试将JavaScript对象数组转换为带有参数的URL字符串,如下所示:

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

表面上看,上面的代码可以工作。但存在一个问题。

问题

如您所见,我有两个嵌套的forEach循环。为了更好的性能,我希望知道如何避免这种嵌套,而是只使用一个forEach循环。

如何使用仅一个循环实现相同的结果?

英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

let entry_arr = [];

objects.forEach(obj =&gt; {
  Object.entries(obj).forEach(entry =&gt; {
    entry_arr.push(entry.join(&#39;=&#39;));
  });
});

let entry_str = entry_arr.join(&#39;&amp;&#39;);

console.log(entry_str);

<!-- end snippet -->

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?

答案1

得分: 2

将数组中的每个对象合并到一个主对象中似乎是我唯一能想到的解决方案。(我假设lastName: paris是一个拼写错误)

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);
英文:

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)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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

const entry_str = Object.entries(obj).map(entry =&gt; 
    entry.join(&#39;=&#39;)
  ).join(&#39;&amp;&#39;);

console.log(entry_str);

<!-- end snippet -->

答案2

得分: 1

答案由Nina提供,仍然使用嵌套循环,而不是使用forEach,使用了map。

对于特殊字符处理,我强烈建议使用URLSearchParams类。

我建议将对象数组连接为一个单一对象,然后使用reduce导入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());
英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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

<!-- end snippet -->

答案3

得分: 0

至少需要将条目与连接键和值进行映射,并连接嵌套的条目和外部数组。

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

请注意,这是你提供的代码的翻译部分。

英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月9日 18:23:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定