-6

I am facing a difficulty to loop through an object (the object also contains array in different layers) with at least 6 layers and show key/value pairs. , I tried to use For...In statement or recursion to loop through it. Sadly, it was not successful. Could anyone kindly provide the solution for me please, thank you very much.

  1. Recursive Function
function keyValuePairFunc(obj) {
    for (const [key, value] of Object.entries(obj)) {
      console.log(`${key}: ${value}`)
      if (typeof value === "object") {
        for (const [key, val] of Object.entries(value)) {
          console.log(`${key}: ${val}`)
        }
      }
            
    }
  }

keyValuePairFunc(loadedData);
  1. Object needed to be loop through enter image description here
tsungjen
  • 5
  • 3
  • 6
    Your recursive function literally isn't recursive. Inside the `if` you should call `keyValuePairFunc(value)`. – Luatic Jun 29 '22 at 13:55
  • Possible duplicate of [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383/218196) – Felix Kling Jun 29 '22 at 13:56
  • can you add the object please? – subodhkalika Jun 29 '22 at 13:58
  • @FelixKling Is there a reason you're not using the close link? – Heretic Monkey Jun 29 '22 at 13:58
  • 2
    Regarding @subodhkalika's comment: [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Heretic Monkey Jun 29 '22 at 14:15
  • @HereticMonkey: Sometimes I feel conflicted about these questions and don't want to close them immediately. It would be nice if I'd have the option to cast a "normal" close vote. In this case the OP seems to know how to iterate but maybe not how to write a recursive function. – Felix Kling Jun 29 '22 at 14:36
  • @FelixKling I would say that if that's the case, they can edit their question to make that clear, and the question would go into the reopen queue. But maybe it's good I don't have a gold badge ;). – Heretic Monkey Jun 29 '22 at 19:43
  • @HereticMonkey thank you for the suggestion, I am not familiar with stackoverflow and will improve it when I asking a question. – tsungjen Jun 30 '22 at 08:02

1 Answers1

0

I believe you are almost there.

When comparing typeof val === "object", please note that null is also treated as a object type in Javascript. So please make sure you do a null check on your solution. If you try to do Object.entries(null), it gives Uncaught TypeError: Cannot convert undefined or null to object

var loadedData = {
          b: {x:1, c:3, d: [{x: null}]},
          r: {e:[{s:[34]}], f:{t: 4}, g: [{rr: 2}]}
       }
         const keyValuePairFuncs = (obj) => {
                if(!obj) return;  // Added a null check for  Uncaught TypeError: Cannot convert undefined or null to object
                for (const [key, val] of Object.entries(obj)) {
                    console.log(`${key}: ${JSON.stringify(val)}`)
                    if (typeof val === "object") {
                        keyValuePairFuncs(val);   // recursively call the function
                    }
                }
            
          }
        
        keyValuePairFuncs(loadedData);
subodhkalika
  • 1,964
  • 1
  • 9
  • 15
  • thank you for your reply. Your code is worked itself, but not for my current situation. I use React.js and the app cannot be rendered successfully with the error message -> Uncaught TypeError: Cannot convert undefined or null to object, if I use recursion in the keyValuePairFuncs. – tsungjen Jun 29 '22 at 15:30
  • That is because JS treats `null` as an object and if you try `Object.entries(null)` the you get error. Solution is to simply put a null check – subodhkalika Jun 29 '22 at 23:13
  • Thank you and it works. Now I try to push the key/value pairs from all layers to an array, but seems it only can push the data of first layer. I declare an array named result and put `result.push([key, value]);` to the for...of statement. – tsungjen Jun 30 '22 at 07:55