7

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

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.

jureispro
  • 1,342
  • 5
  • 22
  • 43
  • http://stackoverflow.com/questions/2250953/how-do-i-create-javascript-arrayjson-format-dynamically – Vedant Terkar Dec 29 '14 at 19:37
  • this code doesn't end up with `rv` being empty, unless `dbInfo.emails` is empty. I just tested it. – forgivenson Dec 29 '14 at 19:47
  • I can't even make sense of the way the OP has presented the desired input and output – Alnitak Dec 29 '14 at 19:53
  • Is the goal here to store the name and multiple email addresses for a user? If so, the data structure should be changed. The `id`, `firstname` and `lastname` properties are fine, but you should have an `email` property that is an array, containing the multiple email addresses. – Jonathan M Dec 29 '14 at 19:58

4 Answers4

10

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 }

Alnitak
  • 334,560
  • 70
  • 407
  • 495
5

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]);
Vicruz
  • 321
  • 1
  • 12
1

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] };
    }
}
forgivenson
  • 4,394
  • 2
  • 19
  • 28
0

this work perfectly //Option Select

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

  console.log(range);
Noman
  • 887
  • 1
  • 15
  • 34