0

I have an array that looks something like this:

var a = [
    {
      value: 'Some data',
      structure: 'linear',
      id: 0,
      children: [
        { id: 1, value: 'Some data', structure: undefined },
        { id: 2, 
          value: 'Some data',
          structure: 'linear', 
          children: [ 
           { id: 4, value: 'Some data', structure: undefined } 
          ] 
        }
      ]
    },
    {
      id: 5,
      structure: undefined
      value: 'Some data',
    },
   ];

I am trying to remove all the objects which value of structure is undefined. Every matching object with no children, or matches in children hierarchy, should not exist in output array. I don't know at run time how many levels of objects will have a children array

The output should look something like this:

const output = [
 {
   value: 'Some data',
   structure: 'linear',
   id: 0,
   children: [
    { id: 2, value: 'Some data', structure: 'linear' }
   ]
 }
];
Sanjita
  • 103
  • 5

1 Answers1

-1

Map over the data recursively and then return the result after filtering the undefined values like

var a = [
  {
    value: 'Some data',
    structure: 'linear',
    id: 0,
    children: [
      { id: 1, value: 'Some data', structure: undefined },
      {
        id: 2,
        value: 'Some data',
        structure: 'linear',
        children: [
          { id: 4, value: 'Some data', structure: undefined }
        ]
      }
    ]
  },
  {
    id: 5,
    structure: undefined,
    value: 'Some data',
  },
];
const getReducedArr = (data) => {
  return data.map((obj) => {
    if (obj.structure) {
      const children = obj.children ? getReducedArr(obj.children) : [];
      return {
        ...obj,
        ...(children.length > 0 ? { children } : undefined)
      }
    }
  }).filter(data => data !== undefined)
}

const res = getReducedArr(a);


console.log(res)
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400