如果JSON中的所有元素都为空,我如何使用JavaScript删除对象

n7taea2i  于 2023-08-08  发布在  Java
关注(0)|答案(3)|浏览(109)

你能告诉我如何使用JavaScript删除json中所有null值的对象吗?
我需要删除嵌套的对象与null/空键太。

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
              "text": null,
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                         "definition": null
                    },
                    "GlossSee": "markup",
                    "window": {
                        "title": "Sample Konfabulator Widget",
                        "description": ""
                    }
                }
            }
        },
        "image": {
            "src": null,
            "name": null,
            "alignment": null
        },
        "text": {
            "data": "Click Here",
            "size": null,
            "style": "bold",
            "name": "text1",
            "hOffset": "",
            "vOffset": "",
            "alignment": "center",
            "onMouseUp": null
        }
    }
}

字符串
需要如下输出:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook."
                    },
                    "GlossSee": "markup",
                    "window": {
                        "title": "Sample Konfabulator Widget"
                    }
                }
            }
        },
        "text": {
            "data": "Click Here",
            "style": "bold",
            "name": "text1",
            "alignment": "center"
        }
    }
}


如何在整个json中删除null或空键的对象,甚至是递归的。比如image对象,它的键为空或null值。

km0tfn4u

km0tfn4u1#

使用JSON.stringify(value, replacer)/JSON.parse(text, reviver)中的replacer/reviver可以获得更接近的结果

使用JSON.stringify的示例

let data = {"glossary":{"title":"example glossary","GlossDiv":{"title":"S","text":null,"GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","definition":null},"GlossSee":"markup","window":{"title":"Sample Konfabulator Widget","description":""}}}},"image":{"src":null,"name":null,"alignment":null},"text":{"data":"Click Here","size":null,"style":"bold","name":"text1","hOffset":"","vOffset":"","alignment":"center","onMouseUp":null}}}

let json = JSON.stringify(data, (key, value) => {
    return (value === null || value === '') ? undefined : value
}, 4)

console.log(json)

字符串

t5fffqht

t5fffqht2#

您可以通过递归方式检查键的类型,然后选择保留或删除所述键来完成此操作。
您可能还希望剔除undefined值,这可以通过更松散的检查,例如data == null将检查nullundefinedhttps://stackoverflow.com/a/359629/15291770

const data = {
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "text": null,
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "definition": null
          },
          "GlossSee": "markup",
          "window": {
            "title": "Sample Konfabulator Widget",
            "description": ""
          }
        }
      }
    },
    "image": {
      "src": null,
      "name": null,
      "alignment": null
    },
    "text": {
      "data": "Click Here",
      "size": null,
      "style": "bold",
      "name": "text1",
      "hOffset": "",
      "vOffset": "",
      "alignment": "center",
      "onMouseUp": null
    }
  }
}

const removeKeysWithNullValues = (data) => {
  if (data === null || typeof data !== 'object') {
    return data;
  }

  if (Array.isArray(data)) {
    return data.map(item => removeKeysWithNullValues(item));
  }

  const newData = {};
  for (const key in data) {
    const value = removeKeysWithNullValues(data[key]);
    if (value !== null) {
      newData[key] = value;
    }
  }

  return Object.keys(newData).length > 0 ? newData : null;
}

const result = removeKeysWithNullValues(data);
console.log(result);

字符串

3okqufwl

3okqufwl3#

let obj = {
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "text": null,
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "definition": null
          },
          "GlossSee": "markup",
          "window": {
            "title": "Sample Konfabulator Widget",
            "description": ""
          }
        }
      }
    },
    "image": {
      "src": null,
      "name": null,
      "alignment": null
    },
    "text": {
      "data": "Click Here",
      "size": null,
      "style": "bold",
      "name": "text1",
      "hOffset": "",
      "vOffset": "",
      "alignment": "center",
      "onMouseUp": null
    }
  }
};

function nested(data) {
  for (let x in data) {
    // console.log(data[x]);
    if (typeof data[x] == 'object') {
      nested(data[x]);
    }
    if (data[x] == null) {
      delete data[x];
    }
  }
}
nested(obj);

//filter out empty object 
function filterout(obj) {
  for (let j in obj) {
    if (typeof obj[j] == 'object') {
      filterout(obj[j])
    }
    if (!Object.keys(obj[j]).length) {
      delete obj[j];
    }

  }
}
filterout(obj);

console.log(obj);

字符串

相关问题