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

5
  • 1
    see: How to find a node in a tree with JavaScript Commented Oct 27, 2021 at 22:59
  • Do you want to extract/unpack the innermost 'items' ? Commented Oct 27, 2021 at 23:00
  • @emreozgun10 yes i want to innermost 'items' Commented Oct 27, 2021 at 23:06
  • you can find the function from the link @pilchard provided above. I'm preparing one (mine extracts every value, without matching the 'key' ) needs refactoring. Commented Oct 27, 2021 at 23:08
  • im reviewing it. Commented Oct 27, 2021 at 23:10

2 Answers 2

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

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

Comments

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);

Comments

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.