循环遍历对象并推送到数组中

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

Loop through Object and push into Array

问题

我想循环遍历对象并在JavaScript中将这些对象添加到数组中。

  1. // 我的对象:
  2. var raw_data = {
  3. name: "Mike",
  4. age: "27",
  5. };
  6. var array_data = [];
  7. // 然后我遍历对象:
  8. for (let [key, name] of Object.entries(raw_data)) {
  9. if (name !== "") {
  10. array_data.push({
  11. email: `${raw_data.name}`,
  12. password: `${raw_data.age}`,
  13. });
  14. }
  15. }
  16. console.log(array_data);

我的输出是:

  1. [
  2. { email: 'nang@gmail.com', password: '1234567' },
  3. { email: 'nang@gmail.com', password: '1234567' }
  4. ]

我希望只得到一个插入:

  1. [
  2. { email: 'nang@gmail.com', password: '1234567'}
  3. ]

请问如何做到这一点?

英文:

I am looking to loop the object and want to add those object in array in Javascript.

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

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

  1. //My Object:
  2. var raw_data = {
  3. name: &quot;Mike&quot;,
  4. age: &quot;27&quot;,
  5. };
  6. var array_data = [];
  7. //Then I loop through the object:
  8. for (let [key, name] of Object.entries(raw_data)) {
  9. if (name !== &quot;&quot;) {
  10. array_data.push({
  11. email: `${raw_data.name}`,
  12. password: `${raw_data.age}`,
  13. });
  14. }
  15. }
  16. console.log(array_data);

<!-- end snippet -->

My out put is :

  1. [
  2. { email: &#39;nang@gmail.com&#39;, password: &#39;1234567&#39; },
  3. { email: &#39;nang@gmail.com&#39;, password: &#39;1234567&#39; }
  4. ]

I would like expect to get only one insert:

  1. [
  2. { email: &#39;nang@gmail.com&#39;, password: &#39;1234567&#39;}
  3. ]

Could you please help me how to get that?

答案1

得分: 1

我认为你想要这个,只需将一个对象推入一个数组中,并借助 map 方法循环遍历数组,用你想要的键替换你的键

  1. var raw_data = {
  2. name: "Mike",
  3. age: "27",
  4. };
  5. var array_data = [];
  6. array_data.push(raw_data);
  7. var new_array = array_data.map(item => {
  8. return { email: item.name, password: item.age };
  9. });
  10. console.log(new_array);
英文:

I think you want this, just push an object into an array and with the help of map method loop through the array to replace your keys with your desired ones

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

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

  1. var raw_data = {
  2. name: &quot;Mike&quot;,
  3. age: &quot;27&quot;,
  4. };
  5. var array_data = [];
  6. array_data.push(raw_data);
  7. var new_array = array_data.map(item =&gt; {
  8. return { email: item.name, password: item.age };
  9. });
  10. console.log(new_array);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 12:21:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378636.html
匿名

发表评论

匿名网友

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

确定