DEV Community

druchan
druchan

Posted on

Using object-access instead of Array.find when dealing with lots of data - Javascript Recipe

A repeating thing we do with a large list is try and find a particular item.

For instance, you get a customers list from an API and at various points, you try and extract one particular customer:

let customers = [
  { id: 'asdf', name: 'john', age: 28, city: 'denver' },
  { id: 'lkjh', name: 'bob', age: 25, city: 'kyoto' },
  { id: 'qwer', name: 'angela', age: 44, city: 'mumbai' },
];

let customerIdToFind = 'asdf';

const result = customers.find((cust) => cust.id === customerIdToFind);
// { id: 'asdf', name: 'john', age: 28, city: 'denver' }
Enter fullscreen mode Exit fullscreen mode

There are times when I do this a lot across the app. So instead of trying to find by iterating over a list, I convert the customers list into an object where the key is the id and the value is the customer object.

const convertToObject = ({ key, list = [] }) => {
  if (!list || !list.length || !key) return undefined;
  const kvals = list.map((item) => item[key]).filter((v) => v !== undefined);
  return Object.fromEntries(
    kvals.map((kval) => [kval, list.find((item) => item[key] === kval)])
  );
};

let customers = [
  { id: 'asdf', name: 'john', age: 28, city: 'denver' },
  { id: 'lkjh', name: 'bob', age: 25, city: 'kyoto' },
  { id: 'qwer', name: 'angela', age: 44, city: 'mumbai' },
];

let customersAsObject = convertToObject({
  key: 'id',
  list: customers,
});

/* 
customersAsObject = {
  'asdf': { id: 'asdf', name: 'john', age: 28, city: 'denver' },
  'lkjh': { id: 'lkjh', name: 'bob', age: 25, city: 'kyoto' },
  'qwer': { id: 'qwer', name: 'angela', age: 44, city: 'mumbai' },
}
*/
Enter fullscreen mode Exit fullscreen mode

This makes it easy to "access" a particular customer at O(1) time instead of O(N) time.

let customers = [
  { id: 'asdf', name: 'john', age: 28, city: 'denver' },
  { id: 'lkjh', name: 'bob', age: 25, city: 'kyoto' },
  { id: 'qwer', name: 'angela', age: 44, city: 'mumbai' },
];

let customersAsObject = convertToObject({
  key: 'id',
  list: customers,
});

let customerIdToFind = 'asdf';

const result = customersAsObject[customerIdToFind];
// { id: 'asdf', name: 'john', age: 28, city: 'denver' }
Enter fullscreen mode Exit fullscreen mode

Typically, I convert the customers list right at the time of getting the data from the API (or any other service) and pass the object around across the app.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs