0

I have a list of emails in an array:

["gomand@gmail.com", "terry@yahoo.com", "123Yu@gmail.com"]

How can I loop through the array and push each email into an object as its own property: The object would look like:

{
email1: "gomand@gmail.com",
email2: "terry@yahoo.com",
email3: "123Yu@gmail.com"
}
gyre
  • 16,369
  • 3
  • 37
  • 47
Colin Sygiel
  • 917
  • 6
  • 18
  • 29

9 Answers9

5

one liner:

var object = ['gomand@gmail.com', 'terry@yahoo.com', '123Yu@gmail.com'].reduce((r, e, i) => (r['email'+(i+1)] = e, r), {});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
2

var inputArr = ['gomand@gmail.com', 'terry@yahoo.com', '123Yu@gmail.com'];
var outputObj = {};
var i;

for (i=0; i<inputArr.length; i++) {
    outputObj['email'+i] = inputArr[i];
}

console.log(outputObj);
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
1

This should do it:

var arr = ["gomand@gmail.com", "terry@yahoo.com", "123Yu@gmail.com"];
var emails = {}; 
arr.forEach((e, i) => emails["email" + (i+1)] = e);
console.log(emails);
Titus
  • 22,031
  • 1
  • 23
  • 33
1

You could do this quite easily with Array#reduce:

var emails = ['gomand@gmail.com', 'terry@yahoo.com', '123Yu@gmail.com']

var result = emails.reduce(function (o, e, i) {
  o['email' + ++i] = e
  return o
}, {})

console.log(result)
gyre
  • 16,369
  • 3
  • 37
  • 47
0

You can try this

var ary = [];

function pushToAry(name, val) {
   var obj = {};
   obj[name] = val;
   ary.push(obj);
}

pushToAry("myName", "myVal"); // Here it is for single value u can loop with your array. 
  • Help
Help
  • 650
  • 3
  • 8
0

This is what Array.prototype.reduce is made for

const emails = ['gomand@gmail.com', 'terry@yahoo.com', '123Yu@gmail.com']
console.info(emails.reduce((map, email, idx) =>
  Object.assign(map, { ['email' + (idx + 1)]: email }), Object.create(null)))
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Just curious, is `Object.create(null)` a style choice? – thgaskell Mar 28 '17 at 06:02
  • @thgaskell see http://stackoverflow.com/questions/32262809/is-it-bad-practice-to-use-object-createnull-versus and http://stackoverflow.com/questions/15518328/creating-js-object-with-object-createnull – Phil Mar 28 '17 at 09:41
0

Here is another solution

var emails = ["gomand@gmail.com", "terry@yahoo.com", "123Yu@gmail.com"];
var object = {}; 
emails.forEach(function(value, key){
      object["email" + (key+1)] = value;
});

console.log(object);
Sumon Sarker
  • 2,707
  • 1
  • 23
  • 36
0
obj = {};
for(i=0;i<yourArray.length;i++){
propName = 'email' + i;
obj[propName] = yourArray[i];
}

I believe this should work.

Red Bottle
  • 2,839
  • 4
  • 22
  • 59
0

Please find the updated code attached below

var array=["gomand@gmail.com", "terry@yahoo.com", "123Yu@gmail.com"];

var obj = {
   
};
for (var prop in array) {

obj["email"+(prop+1)] = array[prop];
}
console.log(obj);
134
  • 28
  • 8