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

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

Loop through Object and push into Array

问题

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

// 我的对象:
var raw_data = {
  name: "Mike",
  age: "27",
};

var array_data = [];

// 然后我遍历对象:
for (let [key, name] of Object.entries(raw_data)) {
  if (name !== "") {
    array_data.push({
      email: `${raw_data.name}`,
      password: `${raw_data.age}`,
    });
  }
}
console.log(array_data);

我的输出是:

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

我希望只得到一个插入:

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

请问如何做到这一点?

英文:

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

//My Object:

var raw_data = {
  name: &quot;Mike&quot;,
  age: &quot;27&quot;,
};

var array_data = [];

//Then I loop through the object:

for (let [key, name] of Object.entries(raw_data)) {
  if (name !== &quot;&quot;) {
    array_data.push({
      email: `${raw_data.name}`,
      password: `${raw_data.age}`,
    });
  }
}
console.log(array_data);

<!-- end snippet -->

My out put is :

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

I would like expect to get only one insert:

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

Could you please help me how to get that?

答案1

得分: 1

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

var raw_data = {
  name: "Mike",
  age: "27",
};

var array_data = [];
array_data.push(raw_data);

var new_array = array_data.map(item => {
  return { email: item.name, password: item.age };
});

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

var raw_data = {
  name: &quot;Mike&quot;,
  age: &quot;27&quot;,
};

var array_data = [];
array_data.push(raw_data);

var new_array = array_data.map(item =&gt; {
  return { email: item.name, password: item.age };
});

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:

确定