Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
    
this code doesn't end up with rv being empty, unless dbInfo.emails is empty. I just tested it. –  forgivenson 19 hours ago
    
I can't even make sense of the way the OP has presented the desired input and output –  Alnitak 18 hours ago
    
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 18 hours ago

2 Answers 2

up vote 2 down vote accepted

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 }

share|improve this answer
    
Thank your for help. It's working perfectly. –  jureispro 18 hours ago

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] };
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.