gpt4 book ai didi

javascript - 查看一组对象并从其属性中删除未定义

转载 作者:行者123 更新时间:2023-11-30 09:45:53 26 4
gpt4 key购买 nike

我有一个对象数组,我想从任何对象的任何属性中删除“未定义”。

要从对象中删除未定义,我使用此方法,

 removeNullorUndefined:function(model) {
function recursiveFix(o) {
// loop through each property in the provided value
for (var k in o) {
// make sure the value owns the key
if (o.hasOwnProperty(k)) {
if (o[k] === 'undefined') {
// if the value is undefined, set it to 'null'
o[k] = '';
} else if (typeof (o[k]) !== 'string' && o[k].length > 0) {
// if there are sub-keys, make a recursive call
recursiveFix(o[k]);
}
}
}
}

var cloned = $.extend(true, {}, model);
recursiveFix(cloned);
return cloned;

},

我如何修改它以便它也可以接受对象数组并从中删除“未定义”?

感谢任何输入

最佳答案

只要值是 undefined 而不是 'undefined' 的字符串值,那么一种方法是使用 JSON.stringify .引用属性值:

If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).

因此,您可以将对象字符串化并立即解析它以删除 undefined 值。

注意:此方法将深度克隆整个对象。换句话说,如果需要维护引用,则此方法将不起作用。

var obj = {
foo: undefined,
bar: ''
};
var cleanObj = JSON.parse(JSON.stringify(obj));

// For dispaly purposes only
document.write(JSON.stringify(cleanObj, null, 2));

额外的好处是没有任何特殊的逻辑,它可以在任何深度工作:

var obj = {
foo: {
far: true,
boo: undefined
},
bar: ''
};
var cleanObj = JSON.parse(JSON.stringify(obj));

// For dispaly purposes only
document.write(JSON.stringify(cleanObj, null, 2));

如果它是 'undefined' 的字符串值,您可以使用相同的方法,但使用 replacer 函数:

var obj = {
foo: {
far: true,
boo: 'undefined'
},
bar: ''
};
var cleanObj = JSON.parse(JSON.stringify(obj, replacer));

function replacer(key, value) {
if (typeof value === 'string' && value === 'undefined') {
return undefined;
}

return value;
}

// For dispaly purposes only
document.write(JSON.stringify(cleanObj, null, 2));

关于javascript - 查看一组对象并从其属性中删除未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38907308/

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