簡體   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