Search code examples
javascriptobject

Flatten the object gets the console logged thrice


When I use the code below to flatten the object, I get the console logged thrice. The object is to return or console ONE object i.e. newObj

Can someone tell me what I am doing wrong?

Data Input

const data = {
    id: 09,
    email: '[email protected]',
    contactInfo: {
        name: 'Test1',
        address: {
            city: 'Berlin',
            country: 'Germany'
        }
    }
}

Over here I am Flattening the Object through recursive calls.

const newObj = {}

const getFlattenObj = (data) => {
    Object.keys(data).forEach(key => {
        if (typeof data[key] === 'object') {
            getFlattenObj(data[key]);
        } else {
            newObj[key] = data[key]
        }
    })

    console.log(newObj);
}

getFlattenObj(data);


Solution

  • You are logging inside the getFlattenObj which is a recursive function, since it calls itself when the value of a key is an object.

    So the initial call is one, then the code will encounter the contactInfo key and call getFlattenObj again, so another log, and then that second call will encounter the address key and call getFlattenObj once more. So three calls to getFlattenObj is 3 logs.


    An additional improvement you could add, is to not use a global variable for the newObj but instead pass it or create it inside the method, so you can reuse the function multiple time without having to manually clear the object.

    const data = {
      id: 09,
      email: '[email protected]',
      contactInfo: {
        name: 'Test1',
        address: {
          city: 'Berlin',
          country: 'Germany'
        }
      }
    }
    
    const getFlattenObj = (data, targetObject = {}) => {
      Object.keys(data).forEach(key => {
        if (typeof data[key] === 'object') {
          getFlattenObj(data[key], targetObject);
        } else {
          targetObject[key] = data[key]
        }
      })
      return targetObject;
    }
    
    const newObj = getFlattenObj(data);
    console.log(newObj);