我有这个 json 对象:
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',
},
],
},
};
我创建了下面(javascript和打字稿)辅助函数,它从对象键
items
或one
返回一个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,
}));
};
然后我可以像这样使用它:
const items = getItems('one');
items.map((item) => (
<li>{item.title}</li>
));
我可以简化这个助手并得到相同的结果吗?
Object.values
和 Array.prototype.reduce
获取对象数组,如下所示:
const result = Object.values(data).reduce((acc, curr) => {
acc.push(...curr.items);
return acc
}, []);
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',
},
],
},
};
const result = Object.values(data).reduce((acc, curr) => {
acc.push(...curr.items);
return acc
}, []);
console.log(result);
flatMap
作为单线:
const result = Object.values(data).flatMap(o => o.items);
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',
},
],
},
};
const result = Object.values(data).flatMap(o => o.items);
console.log(result);