首页 > 解决方案 > Javascript 整理数据

问题描述

我有一系列具有这种形状的对象...

type allRecipes = {
  rows: [
    {
      category: string;
      id: number;
      owner: string;
      recipes_uri: string;
      recipes_name: string;
    }
  ];
};

许多食谱有相同recipes_name的和相同的,category但有不同的idownerrecipes_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
}

标签: javascript

解决方案


与其检查是否包含在数组中(即 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, });
    }
}

推荐阅读