Converting an array to objects using JavaScript / AngularJS

I need to convert arrays inside my parent array to objects according to the data in my database model.

I have an array like this:

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 an array of email addresses to an array of such objects:

    emails: Array[2] 
    0: 
{
name: "example@mail.com"
}
    1: 
{
name: "otherexample@mail.com"
}
    id: 1 
    firstname: "Jane"
    lastname: "Doe

I tried using this code to convert an array to an object, but for some reason it fails (data is not displayed -> rv variable is empty):

 var rv = {};
        for (var i = 0; i < dbInfo.emails.length; ++i)
            if (dbInfo.emails[i] !== undefined) rv[i] = dbInfo.emails[i];

Does anyone know why my code crashes, and does anyone know a solution to this type of problem?

Thanks in advance.

+4
source share
4 answers

Array.prototype.map:

dbInfo.emails = dbInfo.emails.map(function(e) {
    return { name: e };
});

. (e) { name: email }

+7

, , angular.extend. angular.extend . .

var newObj = {};
angular.extend(newObj,[Array here]);
+4

. .

for (var i = 0; i < dbInfo.emails.length; ++i) {
    if(dbInfo.emails[i] !== undefined) {
        dbInfo.emails[i] = { name: dbInfo.emails[i] };
    }
}
+1

. , , :

dbInfo.emails = dbInfo.emails.map(function(e) {
    var obj = {};
    obj[e] = true; // any value can be defined here.
    return obj;
});
0

Source: https://habr.com/ru/post/1569339/


All Articles