繁体   English   中英

在JavaScript中将数组转换为对象

[英]Transforming array into a object in JavaScript

我正在尝试将数组转换为旨在与AngularJS中的输入复选框配合使用的javscript对象。

这是我从后端获得的输入数组:

let selectedRolesDB = ['ADMIN', 'SECURITY'];

这是我的前端期望:

let selectedRoles =
  {
    'ADMIN' : true,
    'SECURITY': true
  };

我尝试了其他方法,例如angular.forEach,但问题是我无法获得所需的输出:

angular.forEach(selectedRolesDB,(value, key) => {
    this.selectedRoles.push({value : true });
});

谁能告诉我如何最好地解决我的问题,以便最终获得前端期望的阵列?

的jsfiddle

使用array.reduce

  let selectedRolesDB = ['ADMIN', 'SECURITY']; const newArray = selectedRolesDB.reduce((accumulator, value) => { accumulator[value] = true; return accumulator; }, {}); console.log(newArray) 

有关其文档,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

selectedRoles不是数组,而是对象。 将其初始化为空对象:

let selectedRoles = {};

angular.forEach(selectedRolesDB,(value, key) => {
    // use [] notation to add property with required name and value
    selectedRoles[value] = true;
});

最好使用array的本机“ forEach”方法(它具有良好的浏览器支持,请参见Array forEach )。 如果您决定将项目迁移到Angular2 +,这也将有所帮助,因此避免使用'angular.someMethod'是更好的方法。 这是最终解决方案:

const selectedRoles: {[key: string]: boolean} = {};
selectedRolesDB.forEach((value: string) => selectedRoles[value] = true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM