0

I have this utility function that given an array and the key by which it each item should be indexed, should convert it to an object:

export const convertArrayToObject = (array: any[], key: string): any => {
  const initialValue = {};
  return array.reduce((obj, item) => ({
    ...obj,
    [item[key]]: item,
  }), initialValue);
};

Here's what you should expect from this utility:

>>> console.log(convertArrayToObject(
  [
    {
      id: 'foo',
      color: 'blue'
    },
    {
      id: 'bar',
      color: 'red'
    }
  ], 'id'
));

This should log:

{
    foo: {
        id: 'foo',
        color: 'blue'
    },
    bar: {
        id: 'bar',
        color: 'red'
    }
}

The problem is, I'm using any twice and that breaks type safety for no good reason. I'm trying to write this utility function using generics but really finding it hard. Can someone help me replace the two anys with generics?

1 Answer 1

1

You should be able to do this with generics. Example:

function convertArrayToObject<T extends {[key: string]: any}>(array: T[], key: string): {[key: string]: T} {
  const obj: {[key: string]: T} = {};
  array.forEach(item => {
    obj[item[key]] = item
  });

  return obj;
}

console.log(convertArrayToObject(
  [
    {
      id: 'foo',
      color: 'blue'
    },
    {
      id: 'bar',
      color: 'red'
    }
  ], 'id'
));

Alternatively, you could use Object.fromEntries combined with map:

const obj = Object.fromEntries([
  {
    id: 'foo',
    color: 'blue'
  },
  {
    id: 'bar',
    color: 'red'
  }
].map(item => [item.id, item]));

console.log(obj);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.