Home > Software engineering >  Get name of an object that is empty
Get name of an object that is empty

Time:12-01

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
 }
})

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related