{
"top": [{
"language": "English",
"value": ""
}, {
"language": "German",
"value": "hASTA"
}],
"bottom": [{
"language": "English",
"value": "jfgfjg"
}, {
"language": "German",
"value": "fkjhf"
}],
"In": "12 am",
"Out": "3 am",
"Type": ""
}
大家好,我想删除具有空值的键,我尝试使用,filter
但在 google 表格中显示错误。我只想将数据发送到具有值的 API。
在这种情况下,对于
语言:德语,该值为空,所以我会跳过发送top。到 API。
要发送的json:
{
"bottom": [{
"language": "English",
"value": "jfgfjg"
}, {
"language": "German",
"value": "fkjhf"
}],
"In": "12 am",
"Out": "3 am"
}
使用的代码:
apidata = userdata.filter(function(x) { return x !== "" });
你能指导我如何做到这一点吗?
userdata.filter 不会过滤对象的键。
您可以使用 Array.reduce 创建新对象
const json = {
"top": [{
"language": "English",
"value": ""
}, {
"language": "German",
"value": "hASTA"
}],
"bottom": [{
"language": "English",
"value": "jfgfjg"
}, {
"language": "German",
"value": "fkjhf"
}],
"In": "12 am",
"Out": "3 am",
"Type": ""
};
// returns true if it contains a falsy value
// this function is recursive
function checkFalsy(ptr) {
// If we are dealing with an array
if (ptr instanceof Array) {
return ptr.some(x => checkFalsy(x));
}
// If we have a string
if (typeof ptr === 'string') {
return ptr.length === 0;
}
// If we have an object
if (Object.keys(ptr).length) {
return Object.keys(ptr).some(y => checkFalsy(ptr[y]));
}
// anything else
return !!ptr;
}
const filteredJson = Object.keys(json).reduce((tmp, x) => {
// If we are dealing with an array
if (checkFalsy(json[x]) === false) {
tmp[x] = json[x];
}
return tmp;
}, {});
console.log(filteredJson);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句