2016-10-02 75 views
1
創建JSON對象的數組

比方說,我有兩個數組:的javascript:從連接兩個數組

var meals: ["breakfast", "lunch", "dinner"]; 
    var ingredients: [["eggs", "yogurt", "toast"],["falafel", "mushrooms", "fries"], ["pasta", "cheese"]; 

是否有一個優雅的解決方案創建JavaScript對象的數組,其特點:

var dailySchedule = {"breakfast" : ["eggs", "yogurt", "toast"], 
         "lunch": ["falafel", "mushrooms", "fries"], 
         "dinner": ["pasta", "cheese"] 
} 

我知道它應該是與.reduce的東西,但我一直在撓我的頭怎麼辦...

+0

使用'的(...)'循環:) – BeNdErR

+1

JSON是文本數據,你所追求的是簡單的JavaScript對象。 – vlaz

回答

3

當然,你可以減少它

var meals = ["breakfast", "lunch", "dinner"]; 
 
var ingredients = [ 
 
    ["eggs", "yogurt", "toast"], 
 
    ["falafel", "mushrooms", "fries"], 
 
    ["pasta", "cheese"] 
 
]; 
 

 
var dailySchedule = meals.reduce((a,b, i) => { 
 
\t return a[b] = ingredients[i], a; 
 
},{}); 
 

 
console.log(dailySchedule)
.as-console-wrapper {top : 0}

0

只需使用Array#forEach

forEach()方法每個數組元素一次執行設置功能。

var meals = ["breakfast", "lunch", "dinner"], 
 
    ingredients = [["eggs", "yogurt", "toast"], ["falafel", "mushrooms", "fries"], ["pasta", "cheese"]], 
 
    dailySchedule = {}; 
 

 
meals.forEach(function (k, i) { 
 
    this[k] = ingredients[i]; 
 
}, dailySchedule);   
 

 
console.log(dailySchedule);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

,我能想到的另一種優雅的方式是這樣的;

var meals = ["breakfast", "lunch", "dinner"], 
 
ingredients = [["eggs", "yogurt", "toast"],["falafel", "mushrooms", "fries"], ["pasta", "cheese"]], 
 
    result = Object.assign(...meals.map((m,i) => ({[m]:ingredients[i]}))); 
 
console.log(result);