javascript - Javascript 整理数据
问题描述
我有一系列具有这种形状的对象...
type allRecipes = {
rows: [
{
category: string;
id: number;
owner: string;
recipes_uri: string;
recipes_name: string;
}
];
};
许多食谱有相同recipes_name
的和相同的,category
但有不同的id
,owner
和recipes_uri
。
我需要将这些整理成这个新的形状,以消除一些重复并使数据更易于处理。
type recipesCollated = [
{
category: string;
recipes_name: string;
recipes_collection: [
{
id: number;
owner: string;
recipes_uri: string;
}
];
}
];
所以我试图循环allRecipes.rows
然后我应该使用.reduce
我在评论中删除了一些 sudo 代码......
const recipesCollated = [];
for (let i = 0; i < allRecipes.rows.length; i++) {
// is allRecipes.rows[i].recipes_name in the recipesCollated array??;
// if its not push a new record in with one item in the recipes_collection array
// if it is, loop over recipesCollated.recipes_collection and check to see if the current id is in the array
// if it is, our job is done, if its not insert it into recipesCollated.recipes_collection array
}
解决方案
与其检查是否包含在数组中(即 O(n^2)),不如使用将类别和名称关联到条目数组的映射。如有必要,您始终可以将其转换为数组。例如:
const recipesCollated_ = new Map();
for (const recipe of recipes.rows) {
let category_map = recipesCollated_.get(recipe.category);
if (typeof category_map === 'undefined') {
const new_map = new Map();
recipesCollated_.set(recipe.category, new_map);
category_map = new_map;
}
let recipe_array = category_map.get(recipe.recipes_name);
if (typeof recipe_array === 'undefined') {
const new_arr = [];
category_map.set(recipe.recipes_name, new_arr);
recipe_array = new_arr;
}
recipe_array.push({ recipes_uri: recipe.recipes_uri, owner: recipe.owner, id: recipe.id, });
}
const recipesCollated = [];
for (const [ category, recipes_map, ] of recipesCollated_) {
for (const [ recipe_name, recipes, ] of recipes_map) {
recipesCollated.push({ recipes_name: recipe_name, category: category, recipes_collection: recipes, });
}
}
推荐阅读
- python - Telethon 问题:NameError:未定义名称“事件”
- python - 使用双进度条时 tqdm 打印新行
- flutter - 如何在flutter中导入和使用包?
- reactjs - React hooks-如何使用变量在下拉列表中设置选项
- tensorflow - max_pool2d的参数是什么意思?
- c# - 有没有办法在文本块/文本框对象中选择多行字符串的单行/单词?
- scala - 如何在 Scala 中使用案例类进行映射
- reactjs - 如何从浏览器的地址栏中删除不正确的路由并重定向到 hookrouter 中的 Home 路由?
- javascript - 为什么打开模式时'$el.clientWidth'等于0?(Vue.js)
- javascript - 如何在传单地图上显示第二个图标?