英文:
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: "Mike",
age: "27",
};
var array_data = [];
//Then I loop through the object:
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);
<!-- end snippet -->
My out put is :
[
{ email: 'nang@gmail.com', password: '1234567' },
{ email: 'nang@gmail.com', password: '1234567' }
]
I would like expect to get only one insert:
[
{ email: 'nang@gmail.com', password: '1234567'}
]
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: "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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论