Home > Software design >  Flatten deeply nested array of objects
Flatten deeply nested array of objects

Time:01-19

I have following array of objects

            {
                "_id": "63c6cd09c4836daca5a8ea51",
                "groupBy": "Title Metadata",
                "name": "Search Title Name",
                "tooltip": "Searches for books based on title input",
                "renderNATypes": false,
                "isFrequentlyUsed": true,
                "childFilters": [
                    {
                        "_id": "63c6cd09c4836daca5a8ea1f",
                        "controlType": {
                            "name": "inputbox"
                        },
                    },
                    {
                        "_id": "63c6cd09c42136daca5a8ea1f",
                        "controlType": {
                            "name": "dropdown"
                        },
                    }

                ]
            }
        ]

Output I am expecting is new array with number of child with child properties and also parent property

            [{
                "_id": "63c6cd09c4836daca5a8ea51",
        "child_id": "63c6cd09c4836daca5a8ea1f"
                "groupBy": "Title Metadata",
                "name": "Search Title Name",
                "tooltip": "Searches for books based on title input",
                "renderNATypes": false,
                "isFrequentlyUsed": true,
        "controlType": {"name": "inputbox"}
            },
      {
                "_id": "63c6cd09c4836daca5a8ea51",
        "child_id": "63c6cd09c42136daca5a8ea1f"
                "groupBy": "Title Metadata",
                "name": "Search Title Name",
                "tooltip": "Searches for books based on title input",
                "renderNATypes": false,
                "isFrequentlyUsed": true,
        "controlType": {"name": "dropdown"},
      }
        ]

I have tried lodash flatMap, flatMapDeep and few more vanilla javascript without any success.

Thanks in advance

CodePudding user response:

You can achieve your result by using reduce like this

const flattenByChildFilters = (orig) => orig.reduce((item, cur) => {
    const {childFilters, ...base} = cur;

    const newItems = childFilters.map(({controlType}) => ({
      ...base,
      controlType,
    }));
    cur = [...item, ...newItems];
    return cur;
  }, []);


console.log(flattenByChildFilters([
  {
    _id: '63c6cd09c4836daca5a8ea51',
    groupBy: 'Title Metadata',
    name: 'Search Title Name',
    tooltip: 'Searches for books based on title input',
    renderNATypes: false,
    isFrequentlyUsed: true,
    childFilters: [
      {
        _id: '63c6cd09c4836daca5a8ea1f',
        controlType: {
          name: 'inputbox',
        },
      },
      {
        _id: '63c6cd09c42136daca5a8ea1f',
        controlType: {
          name: 'dropdown',
        },
      },
    ],
  },
]));

  • Related