【问题标题】:Return true, if all its elements are assigned to null. There will be another object with in that object如果它的所有元素都赋值为 null,则返回 true。该对象中将有另一个对象
【发布时间】:2020-01-31 13:48:02
【问题描述】:

要从对象中删除空行,需要通用解决方案。

该对象包含一个列表。

这是我要检查的示例对象

  {
    "test": {
      "id": null
    },
    "testName": null,
    "specimen": {
      "id": null
    },
    "specimenName": null,
    "collectionDate": null,
    "resultDate": null,
    "result": null,
    "finding": null,
    "resultValue": null
  }

这个我试过了,但是里面有列表的时候就不行了。

purgeEmptyRows(obj: any) : boolean {
      let isEmpty = false;
      Object.keys(obj).forEach(key => {
          if (!obj[key]) {
              isEmpty = false;
          }else {
            return true;
          } 
      })
     return isEmpty;
}

【问题讨论】:

  • 我不确定你的意思。如果所有子节点都为空,则父节点 isEmpty = true 对吗?
  • 对象不为空,该对象中的每个元素都为空。正如我在问题中提到的那样。
  • 看看stackoverflow.com/a/38340374/2358409。这应该很容易适应null 值。
  • 那么你的结果会像这样吗? {“测试”:{},“样本”:{},}

标签: angularjs typescript angular6


【解决方案1】:

试试这个,

this.findAndReplace(obj, null, []);    

findAndReplace(obj: any, value: any, replacevalue: any) {           
    for (var x in obj) {
        if (obj.hasOwnProperty(x)) {
            if (typeof obj[x] == 'object') {
                this.findAndReplace(obj[x], value, replacevalue);
            }
            if (obj[x] == value) { 
                obj[x] = replacevalue;
                // break; // uncomment to stop after first replacement
            }
        }
    }
    console.log(JSON.stringify(obj));
}

【讨论】:

  • 这个递归逻辑可以使用。要检查此对象是否所有元素都为空,然后返回 false,否则返回 true,这就是我的问题。没有查找和替换。
  • 哦!我的错..实际上您在问题标题中提到了“从对象中删除空元素”,这就是我感到困惑的原因。
猜你喜欢
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
  • 2020-11-13
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多