使用JavaScript/AngularJS将数组转换为对象 [英] Convert array to objects using JavaScript/AngularJS
问题描述
我需要将父数组中的数组转换为对象以匹配数据库模型数据.
I need convert arrays inside my parent array to objects to match my database model data.
我有这样的数组:
emails: Array[2]
0: "example@mail.com"
1: "otherexample@mail.com"
id: 1
firstname: "Jane"
lastname: "Doe
我要实现的是将电子邮件数组转换为这样的对象数组:
What I want to achieve is to convert emails array to array of objects like this:
emails: Array[2]
0:
{
name: "example@mail.com"
}
1:
{
name: "otherexample@mail.com"
}
id: 1
firstname: "Jane"
lastname: "Doe
我试图使用此代码将数组转换为对象,但是由于某种原因它失败(不显示任何数据->变量rv为空):
I tried to use this code to convert array to object but for some reason it fails (no data are displayed -> variable rv is empty):
var rv = {};
for (var i = 0; i < dbInfo.emails.length; ++i)
if (dbInfo.emails[i] !== undefined) rv[i] = dbInfo.emails[i];
有人知道我的代码为什么失败,有人知道这种类型的问题的解决方案吗?
Does someone knows why my code fails and does someone knows solution for this type of problem?
感谢前进.
推荐答案
这是Array.prototype.map
函数的完美用法:
dbInfo.emails = dbInfo.emails.map(function(e) {
return { name: e };
});
即只需将数组(e
)的每个元素转换为对象{ name: email }
i.e. just convert each individual element of the array (e
) into an object { name: email }
这篇关于使用JavaScript/AngularJS将数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!