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
Yes, you can simplify it:
if you want a typed one:
if you want to be more generic
if you want a full clone (i.e. new list of new items)
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 thegetItems
function. If you would like to define the parameter type of thekey
parameter, you should be usingkeyof typeof data
, which essentially tells typescript that thekey
parameter accepts one of the keys of the data object. The code would look something like thisComing to the second part of your question on a simplified solution, this might help
Check out the complete working code for both the parts of your question.