2016-02-12 121 views
-2

怎麼可以將我的數組轉換:轉換數組對象數組

["Collaboration", "Personal", "Services", "Financial", "Enginerring", "Infrastructure", "Application", "null"] 

對象的數組:

["title": "Collaboration", "title":"Personal", "title":"Services", "title":"Financial", "title":"Enginerring", "title":"Infrastructure", "title":"Application", "title":"null"] 

我做這樣的事情:

var mainmenu = []; 
for(var i=0; menus.length > i;i++){ 
    mainmenu[i] = "{title:"+menus[i]+"}"; 
} 

但我得到了:

["{title:Collaboration}", "{title:Personal}", "{title:Services}", "{title:Financial}", "{title:Enginerring}", "{title:Infrastructure}", "{title:Application}"] 

那麼怎麼可能不用雙引號呢?

+1

什麼你看作爲一個 「對象數組」 並不在JavaScript中存在。你的意思是'[{title:「Collaboration」},{...},...]'? – 2016-02-12 16:43:42

回答

4

嘗試使用.map

var data = ["Collaboration", "Personal", "Services", "Financial", "Enginerring", "Infrastructure", "Application", "null"]; 
 
var result = data.map(function (title) { 
 
    return { title: title }; 
 
}) 
 

 
console.log(result);

在你的代碼的問題,您正在使用String代替Object,刪除"

mainmenu[i] = { title: menus[i] }; 
       ^^^ ^^ ^^  ^^^ 
1

這是因爲您正在創建字符串而不是實際的對象。像這樣創建對象:

mainmenu[i] = { 
    title: menus[i] 
}; 
0

ES6

var data = ["Collaboration", "Personal", "Services", "Financial","Enginerring", "Infrastructure", "Application", "null"]; 
data.map(function(title) { 
    return { 
     title: title 
    } 
}) 

ES5

for(var i = 0;i < data.length;i++) { 
    data[i] = {title: data[i]} 
} 
0

這是一個很好的例子,其中可以使用Array.from()

Array.from()方法從創建一個新的Array實例一個 數組式或可迭代的對象。

在ES6中,類語法允許用戶定義的類的內置和 的子類;因此,類方靜態方法(如 Array.from)通過Array的子​​類「」繼承「」,並創建子類的新實例 而不是Array。

var data = ["Collaboration", "Personal", "Services", "Financial", "Enginerring", "Infrastructure", "Application", "null"]; 
 
console.log(Array.from(data, x => ({title : x})));