对JSON API中的成分和度量进行分组的最佳实践



我使用JSON API用于饮料配方,成分和测量信息结构在单独的键值对中,具有递增的数字,如str成份1,str成份2和strMeasure1, strMeasure2等。我想在成分和测量对一起循环,避免访问null变量,但我不确定分组它们的最佳方法是什么。

我尝试了以下代码来提取数据并对结果进行分组,但我对更好的解决方案持开放态度:

let numberOfIngredient = 1;
let numberOfMeasure = 1;
let ingredientArr = [];
let measureArr = [];
Object.keys(drinkData).forEach((key) => {
if (key === `strIngredient${numberOfIngredient}` && drinkData[key] !== null) {
numberOfIngredient++;
ingredientArr.push(drinkData[key]);
}
if (key === `strMeasure${numberOfMeasure}` && drinkData[key] !== null) {
numberOfMeasure++;
measureArr.push(drinkData[key]);
}
});
for (let i = 0; i < ingredientArr.length; i++) {
console.log(ingredientArr[i], measureArr[i]);
}

将strIngredient和strMeasure对组合在一起以创建每个饮料配方的配料-测量对数组的最有效方法是什么?

假设你想要一个名为Ingredient name和Measure的连接元素,那么一个List of Ingredient Elements ({Ingredient, Measure})

例如,你可以选择一个简单的循环。

let ingredients = {
"strIngredient1": "Watermelon",
"strIngredient2": "Mint",
"strIngredient3": "Grapefruit Juice",
"strIngredient4": "Lime",
"strIngredient5": "Tequila",
"strIngredient6": "Watermelon",
"strIngredient7": "Mint",
"strIngredient8": null,
"strIngredient9": null,
"strIngredient10": null,
"strMeasure1": "1/2 cup",
"strMeasure2": "5",
"strMeasure3": "1/3 Cup",
"strMeasure4": "Juice of 1/2",
"strMeasure5": "1 shot",
"strMeasure6": "Garnish with",
"strMeasure7": "Garnish with",
"strMeasure8": null,
"strMeasure9": null,
"strMeasure10": null
};
let groupedIngredients = {};
for (let ingredientKey in ingredients) {
let ingredientID = ingredientKey.split('strIngredient')[1];
if (ingredientID) {
if (!groupedIngredients['ingredient_' + ingredientID] && ingredients['strIngredient' + ingredientID] !== null && ingredients['strMeasure' + ingredientID]) {
groupedIngredients['ingredient_' + ingredientID] = {
ingredient: ingredients['strIngredient' + ingredientID],
measure: ingredients['strMeasure' + ingredientID]
};
};
}
}

结果如下所示:

{
"ingredient_1": {
"ingredient": "Watermelon",
"measure": "1/2 cup"
},
"ingredient_2": {
"ingredient": "Mint",
"measure": "5"
},
"ingredient_3": {
"ingredient": "Grapefruit Juice",
"measure": "1/3 Cup"
},
"ingredient_4": {
"ingredient": "Lime",
"measure": "Juice of 1/2"
},
"ingredient_5": {
"ingredient": "Tequila",
"measure": "1 shot"
},
"ingredient_6": {
"ingredient": "Watermelon",
"measure": "Garnish with"
},
"ingredient_7": {
"ingredient": "Mint",
"measure": "Garnish with"
}
}

我会说这样的东西将是简短和功能:

Object.entries(obj).reduce((acc, [key, value]) => { 
const [,prefix,id] = key.match(/(.*?)(d+)/i);
acc[prefix] = [...(acc[prefix] || []), value];
return acc;
}, {})

请看这里的例子:https://jsfiddle.net/xcksfj32/1

另外:如果你想过滤空值,你可以这样做:

Object.entries(obj).reduce((acc, [key, value]) => { 
const [,prefix,id] = key.match(/(.*?)(d+)/i);
if (value) {
acc[prefix] = [...(acc[prefix] || []), value];
}
return acc;
}, {})

相关内容

  • 没有找到相关文章

最新更新