0

I have a data array

var data=[{
"key": "KUZEY",
"items": [
    {
        "key": "MARMARA",
        "items": [
            {
                "key": "T100",
                "items": [
                    {
                        "Ref": 1,
                        "ApprovedReserveQuantity": 1
                       
                    }
                ]
            }
        ]
    },
    {
        "key": "MARMARA 2",
        "items": [
            {
                "key": "T100",
                "items": [
                    {
                        "Ref": 2,
                        "ApprovedReserveQuantity": 1
                        
                   }
                ]
            }
        ]
    }
] }]

İ want to get items when i call function. how can do that recursiveMethod?

groupedItems=recursiveMethod(data)

groupedItems==>[{"Ref": 1,"ApprovedReserveQuantity": 1},{"Ref": 2,"ApprovedReserveQuantity": 1}]

Bilal Tüylü
  • 19
  • 1
  • 9

2 Answers2

1
groupedItems:any[]=[];    
recursiveMethod(element){
          if(element.items==null)
            this.groupedItems.push(element)
          if (element.items != null){
              let i;
              for(i=0;  i < element.items.length; i++){
                    this.recursiveMethod(element.items[i]);
              }
         }
    }

it's worked

Bilal Tüylü
  • 19
  • 1
  • 9
0

Couldn't find any 'key' checking in your answer. Even though I don't trust my function completely, and am confused for as why it worked, It can be reusable if you tweak/adjust it.

const extractInnermostByKey = (data, targetKey, res = []) => {
    data.forEach((obj) => {
        for (let key of Object.keys(obj)) {
            if (key === targetKey) {
                // console.log(res);  observe res
                res.shift();
                res.push(...obj[key]);
                return extractInnermostByKey(res, targetKey, res);
            }
        }
    });
    return res;
};

const groupedItems = extractInnermostByKey(data, 'items');

console.log(groupedItems);
emre-ozgun
  • 676
  • 1
  • 7
  • 17