在嵌套数组/对象中查找对象的最快方法 [英] Fastest way to find object in nested array/object

查看:83
本文介绍了在嵌套数组/对象中查找对象的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象数组,这些对象在一个属性上也有数组:

I have the following array of objects who also have an array on one property:

const boards = [
  {
    id: 1,
    name: 'Lorem ipsum',
    tasks: [
      { id: 42, ... },
      { id: 65, ... },
      { id: 24, ... },
    ],
  },
  {
    id: 2,
    name: 'Lorem ipsum',
    tasks: [
      { id: 12, ... },
      { id: 85, ... },
      { id: 14, ... },
    ],
  },
];

我正在寻找一种最佳最有效的方法来查找 task 的索引(及其所在的面板)当然).我提出了以下内容,但我想知道这是否真的是查找 task 时最有效的方法,尤其是当您有大型数据集时,或者是否有更好的搜索方式?

I'm looking for the best and most efficient way to find the index of a task (and the board of where it's in of course). I came up with the following but I wonder if this is really the most efficient way when looking for the task, especially when you have a large dataset, or if there may be a better way to search through?

在我的特殊情况下,董事会人数不多(大多数时候不超过10个,但可能有数百个任务)

In my special case there won't be many boards (most of the time not more then 10, but there may be hundreds of tasks)

const idToFind = 1;

let boardIndex = null;
let taskIndex = null;

boards.some((board, index) => {
  taskIndex = board.tasks.findIndex(task => task.id === idToFind);

  // if it has found the task, assign board index and end lookup
  if (taskIndex > -1) {
    boardIndex = index;
    return true;
  }

  return false;
});

推荐答案

boards 内创建新的任务查找表及其相关索引:

Create a new lookup table of tasks and their associated index inside boards:

var taskIds = {
  12: 1,
  85: 1,
  14: 1,
  42: 0,
  65: 0,
  24: 0
};

从那里开始,找到任务和相关的板仅仅是 O(1) * 2

From there, finding a task and associated board is only O(1) * 2

使用Lodash的示例:

Example using Lodash:

var taskIds = {};
_.each(boards, function(board, index) {
  _.each(board.tasks, function(task) {
    taskIds[task.id] = index;
  });
});

现在,您可以轻松地按固定时间按任务索引找到一块木板:

Now you can easily find a board by task index in constant time:

boards [taskIds [65]]

这篇关于在嵌套数组/对象中查找对象的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆