Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  7] [ 1]  / answers: 1 / hits: 26587  / 10 Years ago, mon, december 29, 2014, 12:00:00

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.


More From » arrays

 Answers
40

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 }


[#68361] Wednesday, December 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;