[英]javascript: create an array of JSON objects from linking two arrays
let's say I have two arrays: 假设我有两个数组:
var meals: ["breakfast", "lunch", "dinner"];
var ingredients: [["eggs", "yogurt", "toast"],["falafel", "mushrooms", "fries"], ["pasta", "cheese"];
Is there an elegant solution to create an array of JavaScript objects which features: 是否有一个优雅的解决方案来创建一个JavaScript对象数组,其特点是:
var dailySchedule = {"breakfast" : ["eggs", "yogurt", "toast"],
"lunch": ["falafel", "mushrooms", "fries"],
"dinner": ["pasta", "cheese"]
}
I know it should be something with .reduce but I keep scratching my head how to do it... 我知道它应该是.reduce的东西,但我一直在摸不着怎么做......
Sure, you could reduce it 当然,你可以减少它
var meals = ["breakfast", "lunch", "dinner"]; var ingredients = [ ["eggs", "yogurt", "toast"], ["falafel", "mushrooms", "fries"], ["pasta", "cheese"] ]; var dailySchedule = meals.reduce( (a,b, i) => { return a[b] = ingredients[i], a; },{}); console.log(dailySchedule)
.as-console-wrapper {top : 0}
Just use Array#forEach
. 只需使用Array#forEach
。
The
forEach()
method executes a provided function once per array element.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; }
Another elegant way that i can think of is this; 我能想到的另一个优雅的方式就是这个;
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.