Home > Back-end >  JavaScript recursive function return object with depth values that are empty/undefined/null
JavaScript recursive function return object with depth values that are empty/undefined/null

Time:10-06

Want to check, how to get the empty/null/undefined fields with depth. i am able to solve without the depth and get back plan object but not sure show a depth can be added to this. Looks this this should be done in the recursive way

Eg :

const test = {
  features: ["newData"],
  externalId: "",
  accessInfo: {
    token: "CSwC",
    expiresAt: "",
    createdAt: "2020-09-30T16:43:46.914Z"
  },
  status: "CONNECTED",
  keyValues: [{
      key: "ACCOUNT",
      values: ["585744"]
    },
    {
      key: "ACCOUNT_URL",
      values: ["https://instagram.com/testtest"]
    },
    {
      key: "ACCOUNT_USERNAME",
      values: ["testAccountTest"]
    }
  ]
};

/*
This is the expected output: 
 {
  externalId: "",
  accessInfo: {
    expiresAt: "",
  }
}
*/

// Here is my attempted solution:
const newData = {};
const emptyObjectValues = (data) => {
  for (const obj in data) {
    if (_.isEmpty(data[obj]) || obj.length === 0) {
      newData[obj] = ""
    } else if (typeof data[obj] === "object") {
      emptyObjectValues(data[obj]);
    }
  }
  return newData;
};

console.log(emptyObjectValues(test))
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

CodePudding user response:

This is using a recursion and an extra parameter path of the tree so far. (The path is defined as array of keys).

const test = {features:["newData"],externalId:"",accessInfo:{token:"CSwC",expiresAt:"",createdAt:"2020-09-30T16:43:46.914Z"},status:"CONNECTED",keyValues:[{key:"ACCOUNT",values:["585744"]},{key:"ACCOUNT_URL",values:["https://instagram.com/testtest"]},{key:"ACCOUNT_USERNAME",values:["testAccountTest"]}]};

function emptyObjectValues(obj) {
  var result = {}

  function iterate(obj, path) {
    path = path || [];
    Object.keys(obj).forEach(function(key) {
      var value = obj[key];
      if (!value) {     // <-- or whatever condition
        var pointer = result;
        for (var i = 0; i < path.length; i  ) {
          var k = path[i];
          pointer[k] = {}
          pointer = pointer[k]
        }
        pointer[key] = value
      } else {
        if (typeof value === 'object' && value !== null) {
          iterate(value, path.concat(key))
        }
      }
    })
  }
  iterate(obj)
  return result;
}


console.log(emptyObjectValues(test))
.as-console-wrapper {
  max-height: 100% !important
}

  • Related