简体   繁体   English

JavaScript 递归 function 返回深度值为空/未定义/空的 object

[英]JavaScript recursive function return object with depth values that are empty/undefined/null

Want to check, how to get the empty/null/undefined fields with depth.想要检查,如何获得具有深度的空/空/未定义字段。 i am able to solve without the depth and get back plan object but not sure show a depth can be added to this.我能够在没有深度的情况下解决并取回计划 object 但不确定是否可以添加深度。 Looks this this should be done in the recursive way看起来这应该以递归方式完成

Eg:例如:

 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>

This is using a recursion and an extra parameter path of the tree so far.到目前为止,这是使用树的递归和额外参数path (The path is defined as array of keys). (路径定义为键数组)。

 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM