skip to Main Content

I have this json object:

const data = {
  one: {
    items: [
      {
        title: 'Home',
        url: '',
      },
      {
        title: 'Title test',
        url: '/test',
      },
    ],
  },
  two: {
    items: [
      {
        title: 'Title test 2',
        url: '/test2',
      },
      {
        title: 'Title test 2',
        url: '/test2',
      },
    ],
  },
};

I created below (javascript and typescript) helper function which returns an array of items from object key one or two:

interface Item {
  title: string;
  url: string;
}

const getItems = (key?: 'one') => {
  if (key === 'one') {
    return data.one.items.map((item: Item) => ({
      title: item.title,
      url: item.url,
    }));
  }
  return data.two.items.map((item: Item) => ({
      title: item.title,
      url: item.url,
    }));
};

Then I can use it like:

const items = getItems('one');


items.map((item) => (
 <li>{item.title}</li>
));

Can I simplify this helper and get the same result?

2

Answers


  1. Yes, you can simplify it:

    const getItems = (key) => data[key].items;
    

    if you want a typed one:

    const getItems = (key: 'one' | 'two') => data[key].items;
    

    if you want to be more generic

    const getItems = (key: keyof typeof data) => data[key].items;
    

    if you want a full clone (i.e. new list of new items)

    const getItems = (key) => data[key].items.map(x => ({...x}))
    
    Login or Signup to reply.
  2. Regarding the first part of your question, where you say that the code is not working properly, I think you just got confused with the default value and the type for the key parameter of the getItems function. If you would like to define the parameter type of the key parameter, you should be using keyof typeof data, which essentially tells typescript that the key parameter accepts one of the keys of the data object. The code would look something like this

    interface Item {
      title: string;
      url: string;
    }
    
    const getItems = (key: keyof typeof data='one') => {
      if (key === 'one') {
        return data.one.items.map((item: Item) => ({
          title: item.title,
          url: item.url,
        }));
      }
      return data.two.items.map((item: Item) => ({
          title: item.title,
          url: item.url,
        }));
    };
    

    Coming to the second part of your question on a simplified solution, this might help

    const getItemsSimplified = (key: keyof typeof data='one') => {
      return data[key]?.items.map((item: Item) => ({
          title: item.title,
          url: item.url,
        }));
    };
    

    Check out the complete working code for both the parts of your question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search