如何从数组中输出多个结果
我有这个对象数组,最初只有名称和单位字段。我最近添加了一个数组类型的unitConv字段。
我曾经从每个对象中输出一个带有名称和单位的字符串数组。
const ingredients = [
{name: 'wine', unit: 'ml', unitConv: []},
{name: 'salt', unit: 'gr', unitConv: [{unitMeasure: { name: 'spoon'}}, {unitMeasure: { name: 'tea-spoon'}}]},
{name: 'onion', unit: 'piece', unitConv: []},
]
const response = ingredients.map(ing => `${ing.name} [${ing.unit}]`)
这是回应:
["wine [ml]", "salt [gr]", "onion [piece]"]
现在我添加了unitConv,我想查看unitConv对象中是否有任何可用的,并将它们作为选项传递,如下所示:
["wine [ml]", "salt [gr]", "onion [piece]", "salt[spoon]", "salt[tea-spoon]"]
我也想保留盐的初始值,使用'gr'作为单位的那个。所以对于盐,因为我有一个unit和两个unitConv,我想输出它三遍,每个选项。如果其中一个对象没有 unitConv,则 unitConv 字段将显示为空数组,如上例所示。
回答
您可以使用Array#flatMap来创建第二个数组以与第一个数组连接。
const ingredients = [
{name: 'wine', unit: 'ml', unitConv: []},
{name: 'salt', unit: 'gr', unitConv: [{unitMeasure: { name: 'spoon'}}, {unitMeasure: { name: 'tea-spoon'}}]},
{name: 'onion', unit: 'piece', unitConv: []},
]
const response = ingredients.map(ing => `${ing.name} [${ing.unit}]`)
.concat(ingredients.flatMap(({name, unitConv})=>
unitConv.map(x => `${name} [${x.unitMeasure.name}]`)));
console.log(response);