Vikas Bansal Vikas Bansal - 4 months ago 8
Javascript Question

What is the best way to convert an array of strings into an array of objects?

Let's say I have an array of emails:

['a@gmail.com', 'b@gmail.com', 'c@gmail.com']


I need to convert it into an array of objects that looks like this:

[
{
id: 'a@gmail.com',
invite_type: 'EMAIL'
},
{
id: 'b@gmail.com',
invite_type: 'EMAIL'
},
{
id: 'c@gmail.com',
invite_type: 'EMAIL'
}
]


In order to do that, I have written the following code:

$scope.invites = [];

$.each($scope.members, function (index, value) {
let inviteMember = {
'id': value,
invite_type: 'EMAIL'
}

$scope.invites.push(inviteMember);
});


Is there any better way of doing this?

Answer

Since you're already using jQuery, you can use jQuery.map() like this:

var originalArray = ['a@gmail.com', 'b@gmail.com', 'c@gmail.com']

var newArray = jQuery.map(originalArray, function(email) {
    return {
        id: email,
        invite_type:'EMAIL'
    };
});

jQuery.map() translates all items in a given array into a new array of items. The function I am passing to jQuery.map() is called for every element of the original array and returns a new element that is written to the final array.

There is also the native Array.prototype.map() which is not supported in IE8. If you're not targeting IE8 or if you use a polyfill, then you can use the native .map():

var newArray = originalArray.map(function(email) {
    return {
        id: email,
        invite_type:'EMAIL'
    };
});