简化返回对象数组的 JavaScript / Typescript 辅助函数

问题描述 投票:0回答:1

我有这个 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>
));

我可以简化这个助手并得到相同的结果吗?

javascript arrays json helper
1个回答
0
投票

您可以使用

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);

© www.soinside.com 2019 - 2024. All rights reserved.