0

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.

9
  • First, your question is a bit unclear. Second, array is of type "object". Third, you are overwriting values and not adding in various levels Commented Sep 7, 2022 at 10:31
  • Another issue with your code for which you are getting error is that data is an array. So data.DefaultValue is undefined. You will have to do data[0].DefaultValue For your reference: codesandbox.io/s/weathered-sunset-m7q9yp Commented Sep 7, 2022 at 10:37
  • Thanks for notes. So backend is returning me data which have nested defaultValue objects (some time it can be nested 5 times another time 3 time ..etc) ....I need just understand the count and print them in array like this ["DefaultValue", "DefaultValue", "DefaultValue","DefaultValue","DefaultValue","DefaultValue"] Commented Sep 7, 2022 at 10:42
  • in my case it nested 6 times, that why I am printing array which have 6 defaultvalue Commented Sep 7, 2022 at 10:44
  • 1
    So to understand correct, you only care about DefaultValue? or all keys in general Commented Sep 7, 2022 at 10:46

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

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.