HJ1990
HJ1990

Reputation: 415

Javascript map over nested children

I would like to extract only certain properties from a nested object. For example, I would like a new array that does not include the 'percentDone', 'rollup' & 'color'. Using the map function, I'm not sure how to access all the nested children.

const tasks = [
  {
    id: 1000,
    name: 'Launch SaaS Product',
    percentDone: 50,
    startDate: '2019-01-14',
    expanded: true,
    children: [
      {
        id: 1,
        name: 'Setup web server',
        percentDone: 50,
        duration: 10,
        startDate: '2019-01-14',
        rollup: true,
        endDate: '2019-01-23',
        expanded: true,
        children: [
          {
            id: 11,
            name: 'Install Apache',
            percentDone: 50,
            startDate: '2019-01-14',
            rollup: true,
            duration: 3,
            color: 'teal',
            endDate: '2019-01-17',
            cost: 200,
            baselines: [
              {
                startDate: '2019-01-13T23:00:00',
                endDate: '2019-01-16T23:00:00'
              },
              {
                startDate: '2019-01-13T23:00:00',
                endDate: '2019-01-16T23:00:00'
              },
              {
                startDate: '2019-01-13T23:00:00',
                endDate: '2019-01-16T23:00:00'
              }
            ]
          }
        ],
        baselines: [
          {
            startDate: '2019-01-13T23:00:00',
            endDate: '2019-01-22T23:00:00'
          },
          {
            startDate: '2019-01-13T23:00:00',
            endDate: '2019-01-22T23:00:00'
          },
          {
            startDate: '2019-01-13T23:00:00',
            endDate: '2019-01-22T23:00:00'
          }
        ]
      }
    ],
    endDate: '2019-03-16',
    baselines: [
      {
        startDate: '2019-01-13T23:00:00',
        endDate: '2019-03-15T23:00:00'
      },
      {
        startDate: '2019-01-13T23:00:00',
        endDate: '2019-03-15T23:00:00'
      },
      {
        startDate: '2019-01-13T23:00:00',
        endDate: '2019-03-15T23:00:00'
      }
    ]
  }
];

Something like this but this not include all the nested children.

 var x = tasks.map(item => {
      return {
        name: item.name,
        StartDate: item.StartDate,
        etc... 
        children: item.children.map(x => ({ 
          name: x.name,
          StartDate: x.StartDate,
    
        }))
      }  
    });

Upvotes: 0

Views: 347

Answers (1)

tenshi
tenshi

Reputation: 26326

I would extract it to a different function but you could also inline it like this:

    var x = tasks.map(function mapper(item) {
      return {
        name: item.name,
        StartDate: item.StartDate,
        // etc... 
        children: item.children.map(mapper),
      }  
    });

Upvotes: 1

Related Questions