Convert array to objects using JavaScript/AngularJS

All we need is an easy explanation of the problem, so here it is.

I need convert arrays inside my parent array to objects to match my database model data.

I have array like this:

emails: Array[2] 
0: "[email protected]"
1: "[email protected]"
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: "[email protected]"
}
    1: 
{
name: "[email protected]"
}
    id: 1 
    firstname: "Jane"
    lastname: "Doe

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?

Thanks advance.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

This is a perfect use for the Array.prototype.map function:

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

i.e. just convert each individual element of the array (e) into an object { name: email }

Method 2

I think what are you looking for was angular.extend. For a good article about angular.extend click here. For documentation click here .

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

Method 3

You are putting the emails into an object. Instead, you want to wrap each email in its own object, and put it back in the array.

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

Method 4

this work perfectly
//Option Select

  var range = [];
    for (var i=1; i<$scope.totalItems+1; i++) {
      range.push({value:i});
    }  

  console.log(range);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply