想檢查一下,如何獲得具有深度的空/空/未定義欄位。我能夠在沒有深度的情況下解決并取回計劃物件,但不確定是否可以添加深度。看起來這應該以遞回方式完成
例如:
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/[email protected]/lodash.min.js"></script>
uj5u.com熱心網友回復:
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512809.html
下一篇:按多列分組陣列
