【问题标题】:object key not showing when the value is undefined当值未定义时,对象键不显示
【发布时间】:2021-10-28 08:43:27
【问题描述】:

我有一个具有 +20 个属性的对象。

  export interface FinancialAccountInputModel { 
               id?: number;
               code?: string;
               ... }
financialAccount: FinancialAccountInputModel = {};

这些属性中的一些被设置为一个值,而一些是未定义的。我console.log(financialAccount)时没有显示那些没有值的属性的“键”!如何将那些未显示的键值设置为null

【问题讨论】:

  • 这可能会有所帮助:Object.keys(yourObj).forEach( key => yourObj[key] === undefined ? null : yourObj[key] )
  • 这仍然适用于有价值的人! @capchuck
  • 用例子写成aswer :)

标签: typescript object null undefined key-value


【解决方案1】:

const o = {
  undefKey: undefined,
  nullishKey: null,
  valueKey: 1
};

Object.keys(o).forEach(key => {
  const value = o[key];
  o[key] = value === undefined ? null : value;
});

console.log(o);

【讨论】:

  • export interface FinancialAccountInputModel { id?: number; code?: string; ... } 这是我的对象,你的代码在我的情况下不起作用!
  • 好的,但是如果您的对象中的这些字段是可选的,您还在等什么。如果它们没有传递给对象,则无法显示它们。
  • 问题是我必须通过 API 以null 发送它们
  • @Qiimiia 那么你需要一个逻辑来为这些字段设置默认值。在设置id的地方,例如,它必须看起来像response.id = idValue || null,或者任何其他方式,因为在TS中似乎有no standard way to set default values to interfaces
  • 哦,真是个无赖!还是谢谢
【解决方案2】:

我会采取以下步骤:

  1. 用 for in 循环遍历对象

  2. 检查每个密钥,是否密钥是假的

  3. 如果键是假的,因为它是未定义的

  4. 将值显式设置为 null

for(let key in Obj){
if(!Obj[key]){
    Obj[key] = null;
}
}

请检查一次,看看它是否适合你

【讨论】:

  • 感谢您的帮助。这不适用于未定义的道具,这会将 false 值转换为 null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多