Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get name of an object that is empty

I would like to get variable name of an object which is empty. How can i get this?

My code

var array = [foo, bar, baz]
array.map((el)=>{
 if(Object.keys(el).length === 0) {
  //give me name of var from an array which is empty
 }
})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There’s no way to get to a variable name from some arbitrary value. But you can supply meta information yourself. For example:

const foo = {a: 42};
const bar = {};
const baz = {b: 451};

// Use an object, instead of an array. With the following syntax
// the variable *creates* a property of the same name.
const configs = {foo, bar, baz};

// find *empty* elements:
const emptyConfigs = Object.entries(configs).reduce((acc, [k, cfg]) => {
  return Object.keys(cfg).length === 0
    ? [...acc, k]
    : acc;
}, []);

console.log(emptyConfigs);

Ref: Object initializer


Alternatively include the information with each array entry. Which has the added benefit that the configs can/could be inlined (and thus don’t have a name). E.g.:

const foo = {a: 42};
const bar = {};
const baz = {b: 451};

const configs = [
  {key: 'foo', cfg: foo},
  {key: 'bar', cfg: bar},
  {key: 'baz', cfg: baz},
  {key: 'unnamed', cfg: {}}, // inlined config
];

const emptyConfigs = configs.reduce((acc, {key, cfg}) => {
  return Object.keys(cfg).length === 0
    ? [...acc, key]
    : acc;
}, []);

console.log(emptyConfigs);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading