0

I have an object like below

     var json = {
      "info": {
      "name": {},
      "addr": {
        "strreet": "NYC",
        "zip": 123456789
       }
     }
   }

I want to return the key where it has empty object, it may be nested for example in above json "name" is empty so I want to write a function and want to return "name" here

I have written a function for that given below

function iterate(obj) {
for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
        if (typeof obj[property] == "object") {
            if (JSON.stringify(obj[property]) === '{}') {
                return property
            } else
                iterate(obj[property]);
        } else {}
    }
}
}

Now I'm calling this function like

var key = iterate(json)
console.log('Key',key)

Now key is printing undefined , any help appreciated.

3 Answers 3

1

You can keep a blank array and keep on pushing the empty properties in it. In the last you will need to return this array for the recursion to work and where you are calling the function recursively you will need to push its content in the empty property array.

var json = {
  "personInfo": {
    "personAttributesInfo": {
      "location": {
        "city": "New york",
        "state": {},
      }
    }
  },
  "dataInfo": {
    "travelPricing": {},
    "cost": {
      "usd": 12345,
      "someother": {},
    }
  }
};

function iterate(obj) {
  var emptyProperties = [];
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (typeof obj[property] == "object") {
        if (Object.keys(obj[property]).length === 0) {
          emptyProperties.push(property);
        } else{
          let x = iterate(obj[property]);
          emptyProperties.push(...x);
        }
      } else {
        continue;
      }
    }
  }
  return emptyProperties;
}

var key = iterate(json)
console.log('Key', key);

Sign up to request clarification or add additional context in comments.

3 Comments

Not working for this json var json = { "personInfo": { "personAttributesInfo": { "location": { "city": "New york" } } }, "dataInfo": { "travelPricing": { }, "cost": { "usd": 12345, } } }
@JohneDoe see the updated answer with an even more complicated object.
What is ` emptyProperties.push(...x);` and why we are using array , i need only first encounter empty object not all
1

function iterate expects something. You have to return from else

return iterate(obj[property]);

var json = {
      "info": {
      "name": {},
      "addr": {
        "strreet": "NYC",
        "zip": 123456789
       }
     }
   }


function iterate(obj) {
for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
        if (typeof obj[property] == "object") {
            if (JSON.stringify(obj[property]) === '{}') {
                return property
            } else
                return iterate(obj[property]);
        } else {}
    }
}
}


var key = iterate(json)
console.log('Key', key)

5 Comments

This will not work for nested, for example check this json var json = { "personInfo": { "personAttributesInfo": { "location": { "city": "New york" } } }, "dataInfo": { "travelPricing": { }, "cost": { "usd": 12345, } } }
It's still returning undefined after code changes suggested by you
@JohneDoe, are getting undefined with the input in the comment?
Yes i'm getting input in the comment
It should return travelPricing
0

This answer uses object-scan.

As indicated as desired by the author in a comment, only the first encounter is returned.

Observations:

  • object-scan will traverse into nested arrays. If that is not desired one could check !Array.isArray(value) in breakFn.
  • If performance is important one could separate the compile and search part of object-scan

// const objectScan = require('object-scan');

const isEmptyObject = (value) => (
  value instanceof Object
  && !Array.isArray(value)
  && Object.keys(value).length === 0
);
const finder = (input) => objectScan(['**'], {
  abort: true,
  rtn: 'key',
  filterFn: ({ value }) => isEmptyObject(value)
})(input).pop();

const json = { personInfo: { personAttributesInfo: { location: { city: 'New york', state: {} } } }, dataInfo: { travelPricing: {}, cost: { usd: 12345, someother: {} } } };

console.log(finder(json));
// => someother
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>

Disclaimer: I'm the author of object-scan

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.