如何在JavaScript中从数组元素创建对象

时间:2017-03-28 05:18:53

标签: javascript

我有一个数组中的电子邮件列表:

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

如何遍历数组并将每封电子邮件作为自己的属性推送到对象中:对象看起来像:

{
email1: "gomand@gmail.com",
email2: "terry@yahoo.com",
email3: "123Yu@gmail.com"
}

9 个答案:

答案 0 :(得分:5)

一个班轮:

var object = ['gomand@gmail.com', 'terry@yahoo.com', '123Yu@gmail.com'].reduce((r, e, i) => (r['email'+(i+1)] = e, r), {});

答案 1 :(得分: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);

答案 2 :(得分:1)

这应该这样做:

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);

答案 3 :(得分:1)

您可以使用Array#reduce轻松完成此操作:

&#13;
&#13;
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)
&#13;
&#13;
&#13;

答案 4 :(得分:0)

你可以试试这个

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. 
  • 帮助

答案 5 :(得分:0)

这是Array.prototype.reduce

做的

&#13;
&#13;
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)))
&#13;
&#13;
&#13;

答案 6 :(得分:0)

这是另一种解决方案

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 7 :(得分:0)

obj = {};
for(i=0;i<yourArray.length;i++){
propName = 'email' + i;
obj[propName] = yourArray[i];
}

我相信这应该有用。

答案 8 :(得分:0)

请查看下面附带的更新代码

-exec-run