JavaScript: convert array of objects to dictionary

Updated: 2024-03-12
1 min read
[javascript typescript]

On This Page

type ObjectWithKeyName = {
  [key: string]: any;
};

// transform array of objects to dict
// use object provided keyName as a key of dict
// expected for each object in array this keyName value is unique
const transformArrayToDict = (objects: ObjectWithKeyName[], keyName: string) => {
  const res: ObjectWithKeyName = {};
  objects.forEach((obj) => {
    res[obj[keyName]] = obj;
  });
  return res;
};