【问题标题】:Get name of an object that is empty获取空对象的名称
【发布时间】:2022-01-07 04:40:44
【问题描述】:

我想获取一个空对象的变量名。我怎样才能得到这个?

我的代码

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

【问题讨论】:

  • 这是不可能的。为什么需要它?
  • 其中一个对象可能由于配置错误而为空。必须知道哪一个用于日志目的。
  • 你能改一下array吗?还是该代码的其他内容?顺序重要吗?
  • 是的,我可以改变任何东西。将值插入数组并在其上映射是我的第一个想法。顺序并不重要。
  • 也许您可以在数组的每个对象中添加一个属性_name,例如对于“foo”对象,您可以像 var foo = { _name: "foo"} 和在您显示的代码中一样对其进行初始化上面你检查 Object.keys(el).length === 1 而不是 0 了,所以如果条件为真你显示 el._name ?

标签: javascript arrays object


【解决方案1】:

没有办法从某个任意值获取变量名。但是您可以自己提供信息。例如:

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

参考:Object initializer


或者将信息包含在每个数组条目中。这具有额外的好处,即配置可以/可以内联(因此没有名称)。例如:

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

【讨论】:

  • 工作,谢谢;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 2010-12-05
  • 2016-09-03
  • 2012-05-24
相关资源
最近更新 更多