使用 JavaScript/AngularJS 将数组转换为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27694873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:50:47  来源:igfitidea点击:

Convert array to objects using JavaScript/AngularJS

javascriptarraysangularjs

提问by jureispro

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

我尝试使用此代码将数组转换为对象,但由于某种原因它失败了(没有显示数据 -> 变量 rv 为空):

 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.

先谢谢了。

回答by Alnitak

This is a perfect use for the Array.prototype.mapfunction:

这是该Array.prototype.map功能的完美使用:

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 }

即只需将数组 ( e) 的每个单独元素转换为一个对象{ name: email }

回答by Vicruz

I think what are you looking for was angular.extend. For a good article about angular.extend click here. For documentation click here .

我想你要找的是angular.extend。有关 angular.extend 的好文章,请单击此处。有关文档,请单击此处

var newObj = {};
angular.extend(newObj,[Array here]);

回答by forgivenson

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] };
    }
}

回答by Noman

this work perfectly //Option Select

这项工作完美//选项选择

  var range = [];
    for (var i=1; i<$scope.totalItems+1; i++) {
      range.push({value:i});
    }  

  console.log(range);