gpt4 book ai didi

javascript - 递归地从 JavaScript 对象中删除空值

转载 作者:行者123 更新时间:2023-12-03 13:07:45 26 4
gpt4 key购买 nike

我有一个 JSON obj,经过一些操作(如删除一些片段),我打印它,一切看起来都很好,除了我有一些 null值(value)观。我该如何删除这些?

我用 JSON.stringify(obj, null, 2)方法打印,这是它的样子:

{
"store": {
"book": [
null,
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
null,
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
null,
"price": 19.95
}
}
}

我希望它更紧凑且非常干净(删除额外的 3 null 值):
{
"store": {
"book": [
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}

最佳答案

我必须解决一个类似的问题,但是我不仅想删除 值,还有 未定义 , , 空字符串 , 空数组 空对象 值,递归地,通过检查嵌套对象和嵌套数组。

以下函数使用 Lo-Dash:

function pruneEmpty(obj) {
return function prune(current) {
_.forOwn(current, function (value, key) {
if (_.isUndefined(value) || _.isNull(value) || _.isNaN(value) ||
(_.isString(value) && _.isEmpty(value)) ||
(_.isObject(value) && _.isEmpty(prune(value)))) {

delete current[key];
}
});
// remove any leftover undefined values from the delete
// operation on an array
if (_.isArray(current)) _.pull(current, undefined);

return current;

}(_.cloneDeep(obj)); // Do not modify the original object, create a clone instead
}

例如,如果您使用以下输入对象调用该方法:
var dirty = {
key1: 'AAA',
key2: {
key21: 'BBB'
},
key3: {
key31: true,
key32: false
},
key4: {
key41: undefined,
key42: null,
key43: [],
key44: {},
key45: {
key451: NaN,
key452: {
key4521: {}
},
key453: [ {foo: {}, bar:''}, NaN, null, undefined ]
},
key46: ''
},
key5: {
key51: 1,
key52: ' ',
key53: [1, '2', {}, []],
key54: [{ foo: { bar: true, baz: null }}, { foo: { bar: '', baz: 0 }}]
},
key6: function () {}
};

它会递归地丢弃所有“坏”值,最后只保留那些携带一些信息的值。
var clean = pruneEmpty(dirty);
console.log(JSON.stringify(clean, null, 2));

{
key1: 'AAA',
key2: {
key21: 'BBB'
},
key3: {
key31: true,
key32: false
},
key5: {
key51: 1,
key52: ' ',
key53: [1, '2'],
key54: [{ foo: { bar: true }}, { foo: { baz: 0 }}]
}
};

希望能帮助到你!

关于javascript - 递归地从 JavaScript 对象中删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18515254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com