Search code examples
javascriptarraysjsonhelper

Simplify a JavaScript / Typescript helper function which returns an array of objects


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?


Solution

  • 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}))