0

Model:

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

Data:

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' }],
    },
  ],
}]

My requirement is to get all the names as an array of string based on the parent name e.g.

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

Similarily

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

I tried dataArray.filter((feedData) => feedData.name === 'FEEDS').map((childData) => childData.children).map((data) => data.name);

However, this failing with error 'Property 'name' does not exist on the type 'FeedNode[]' and the result is undefined.

1
  • dataArray.filter(feed => feed.name === 'FEEDS').reduce((agg, feed) => [...agg, ...feed.children.map(child => child.name)], []) You'll have to call the reduce recursively if you have multiple levels of children Commented Oct 16, 2020 at 20:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks :) this is what I was expecting.
Welcome;) please accept the answer if it worked for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.