JavaScript递归函数返回深度值为空/未定义/null的对象



想要检查,如何获得具有深度的空/空/未定义字段。我能够在没有深度的情况下求解并返回计划对象,但不确定是否可以向其中添加深度。看起来这应该以递归方式完成

例如:

const test = {
features: ["newData"],
externalId: "",
accessInfo: {
token: "CSwC",
expiresAt: "",
createdAt: "2020-09-30T16:43:46.914Z"
},
status: "CONNECTED",
keyValues: [{
key: "ACCOUNT",
values: ["585744"]
},
{
key: "ACCOUNT_URL",
values: ["https://instagram.com/testtest"]
},
{
key: "ACCOUNT_USERNAME",
values: ["testAccountTest"]
}
]
};
/*
This is the expected output: 
{
externalId: "",
accessInfo: {
expiresAt: "",
}
}
*/
// Here is my attempted solution:
const newData = {};
const emptyObjectValues = (data) => {
for (const obj in data) {
if (_.isEmpty(data[obj]) || obj.length === 0) {
newData[obj] = ""
} else if (typeof data[obj] === "object") {
emptyObjectValues(data[obj]);
}
}
return newData;
};
console.log(emptyObjectValues(test))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

到目前为止,这是使用递归和树的额外参数path。(路径定义为键数组(。

const test = {features:["newData"],externalId:"",accessInfo:{token:"CSwC",expiresAt:"",createdAt:"2020-09-30T16:43:46.914Z"},status:"CONNECTED",keyValues:[{key:"ACCOUNT",values:["585744"]},{key:"ACCOUNT_URL",values:["https://instagram.com/testtest"]},{key:"ACCOUNT_USERNAME",values:["testAccountTest"]}]};
function emptyObjectValues(obj) {
var result = {}
function iterate(obj, path) {
path = path || [];
Object.keys(obj).forEach(function(key) {
var value = obj[key];
if (!value) {     // <-- or whatever condition
var pointer = result;
for (var i = 0; i < path.length; i++) {
var k = path[i];
pointer[k] = {}
pointer = pointer[k]
}
pointer[key] = value
} else {
if (typeof value === 'object' && value !== null) {
iterate(value, path.concat(key))
}
}
})
}
iterate(obj)
return result;
}

console.log(emptyObjectValues(test))
.as-console-wrapper {
max-height: 100% !important
}

最新更新