how to flat nested objects keys with reactJS

Viewed 36

Hi everyone I have following code

I want to show my DefaultValue nested objects like this

["DefaultValue", "DefaultValue", "DefaultValue","DefaultValue","DefaultValue","DefaultValue"]

I have following data from backend:

    const data = [
     {
      id: 243,
      Name: "test",
      type: "checkbox",
      DefaultValue: {
        DefaultValue: {
          DefaultValue: {
            DefaultValue: {
              DefaultValue: {
                DefaultValue: ["a"]
              }
            }
          }
        }
      }
     }
    ];

So I am trying to do following, but it's not works, its says like Cannot convert undefined or null to object

    const innerObject = o => {
     return Object.keys(o).reduce(function (r, k) {
      return typeof o[k] === 'object' ? innerObject(o[k]) : ((r[k] = o[k]), r);
     }, {});
    };

Please help me to resolve this problem.

1 Answers

you can try this:

const data = [
     {
      id: 243,
      Name: "test",
      type: "checkbox",
      DefaultValue: {
        DefaultValue: {
          DefaultValue: {
            DefaultValue: {
              DefaultValue: {
                DefaultValue: ["a"]
              }
            }
          }
        }
      }
     }
    ];
    
    const makeArr = (obj, arr = []) =>{
        if(typeof obj === 'object' && obj !== null){
            arr.push('DefaultValue');
           return makeArr(obj.DefaultValue, arr)
        }else{
            return arr;
        }
    }
    
    console.log(makeArr(data[0].DefaultValue))
Related