使用打字稿或JavaScript将对象数组转换为字符串数组

时间:2020-10-16 19:52:17

标签: javascript typescript

型号:

export interface FeedNode {
    name: string;
    children?: FeedNode[];
    }

数据:

const dataArray: FeedNode[] = [
{
  name: 'FEEDS',
  children: [
    { name: 'Pink Vila' },
    { name: 'Dainik bhaskar' },
    { name: 'TOI' },
  ],
},
{
  name: 'BOARDS',
  children: [
    {
      name: 'Top Stories',
      children: [{ name: 'Sports' }, { name: 'Politics' }],
    },
    {
      name: 'Interests',
      children: [{ name: 'Health' }, { name: 'Entertainment' }],
    },
  ],
}]

我的要求是将所有名称作为基于父名称的字符串数组获得

if dataArray.name == 'FEEDS'. expected result = ['Pink Vila','Dainik bhaskar', 'TOI'].

沉默

if dataArray.name == 'BOARDS' expected result = ['Top Stories', Sports', 'Politics', 'Interests', 'Health','Entertainment']

我尝试了dataArray.filter((feedData) => feedData.name === 'FEEDS').map((childData) => childData.children).map((data) => data.name);

但是,在类型'FeedNode []'上不存在错误'Property'name'的失败,并且结果是不确定的。

1 个答案:

答案 0 :(得分:1)

interface FeedNode {
  name: string
  children?: FeedNode[]
}

const dataArray: FeedNode[] = [
  {
    name: 'FEEDS',
    children: [
      { name: 'Pink Vila' },
      { name: 'Dainik bhaskar' },
      { name: 'TOI' },
    ],
  },
  {
    name: 'BOARDS',
    children: [
      {
        name: 'Top Stories',
        children: [{ name: 'Sports' }, { name: 'Politics' }],
      },
      {
        name: 'Interests',
        children: [{ name: 'Health' }, { name: 'Entertainment' }],
      },
    ],
  },
]

function getChildren(dataArray: FeedNode[], name: string): string[] {
  // find the data object with given name
  const data = dataArray.find(data => data.name === name)
  if (!data) return []

  let result: string[] = []

  function _getChildren(data: FeedNode) {
    const children = data.children
    if (!children) return

    children.forEach(c => {
      result.push(c.name) // push this child's name and then its children (DFS)
      _getChildren(c)
    })
  }

  _getChildren(data)
  return result
}

console.log(getChildren(dataArray, 'FEEDS')) // expected
console.log(getChildren(dataArray, 'BOARDS')) // expected

Playground link