You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于数组对象的非空配料与计量属性创建新对象数组?

问题:转换鸡尾酒配料数据结构

给定如下鸡尾酒数据:

const cocktail = [
    {
        "idDrink":"13070",
        "strDrink":"Fahrenheit 5000",
        "strGlass":"Shot glass",
        "strInstructions":"Cover bottom of shot gla",
        "strIngredient1":"Firewater",
        "strIngredient2":"Absolut Peppar",
        "strIngredient3":"Tabasco sauce",
        "strIngredient4":null,
        "strMeasure1":"1/2 oz ",
        "strMeasure2":"1/2 oz ",
        "strMeasure3":"1 dash ",
        "strMeasure4":null
    }
]

需要将其转换为仅包含非空配料与对应分量的数组,每个对象结构为{ measure: 分量值, name: 配料名 },理想输出如下:

[
    {
        measure: '1/2 oz',
        name: 'Firewater'
    },
    {
        measure: '1/2 oz',
        name: 'Absolut Peppar'
    },
    {
        measure: '1 dash',
        name: 'Tabasco sauce'
    },
]

实现方案

方案一:循环遍历索引

这种方式逻辑直观,适合配料索引连续的场景:

// 提取数组中的鸡尾酒对象
const drink = cocktail[0];
const result = [];

let index = 1;
while (true) {
    const ingredientName = drink[`strIngredient${index}`];
    const ingredientMeasure = drink[`strMeasure${index}`];
    
    // 当配料为null时终止循环
    if (!ingredientName) break;
    
    // 去除分量字符串的首尾空格,加入结果数组
    result.push({
        measure: ingredientMeasure?.trim() || '',
        name: ingredientName
    });
    index++;
}

console.log(result);

方案二:通过键值对筛选

这种方式更灵活,即使配料索引不连续也能正常处理:

const drink = cocktail[0];
const result = [];

// 遍历对象所有键值对
Object.entries(drink).forEach(([key, value]) => {
    // 匹配配料字段(如strIngredient1)
    const match = key.match(/^strIngredient(\d+)$/);
    if (match && value) {
        const num = match[1];
        const measure = drink[`strMeasure${num}`];
        result.push({
            measure: measure?.trim() || '',
            name: value
        });
    }
});

console.log(result);

两种方案都会输出符合要求的结果,其中trim()用于去除分量字符串首尾的空格,?.可选链操作符避免因measure为null导致报错。

内容的提问来源于stack exchange,提问作者Lithium

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:15:45