2 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
有趣的遞歸問題。
但源數(shù)據(jù)有點(diǎn)奇怪。數(shù)組項(xiàng)不是鍵值對(duì)象。
應(yīng)該是這樣的:
var a = {
0: {
CLIENTS_EMAIL: null
},
1: {
CLIENTS_PASSWORD: null
},
2: {
CLIENTS_CONFIRMPASSWORD: null
},
3: {
CLIENTS_FIRSTNAME: null
},
4: {
CLIENTS_LASTNAME: null
},
5: {
CLIENTS_MOBILE: null
},
6: {
CLIENTS_HOMEPHONE: null
},
7: {
CLIENTS_BUSPHONE: null
},
8: {
CLIENTS_RECEIVE_MARKETING_VIA: [
{
CLIENTS_ISMARKETINGVIAEMAIL: false
},
{
CLIENTS_ISMARKETINGVIAMAIL: false
},
{
CLIENTS_ISMARKETINGVIAPHONE: false
},
{
CLIENTS_ISMARKETINGVIASMS: false
}
]
}
}
然后使用遞歸
let result = {};
let convert = (obj) => {
for (var i in obj) {
if (obj[i] != null && obj[i] !== false) {
convert(obj[i]);
} else {
result[i] = obj[i];
}
}
}

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
該函數(shù)遞歸地將對(duì)象的對(duì)象合并為單個(gè)對(duì)象,但成本太高。
時(shí)間復(fù)雜度約為O(n 2 log n)
(雖然沒有測(cè)試其他輸入,所以讓我知道它是否不適用于所有內(nèi)容)
let result = {};
recMerge(ooo); /// --> 'ooo' is your (o)bject (o)f (o)bjects
function recMerge(obj) {
Object.getOwnPropertyNames(obj).forEach((prop) => {
const propName = obj[prop];
Object.getOwnPropertyNames(propName).forEach((propValue) => {
if (!!propName[propValue] && typeof propName[propValue] === "object") {
recMerge(propName[propValue]);
} else {
result = { ...result, ...propName };
}
});
});
}
例子
輸出將始終是每次迭代中最內(nèi)部的對(duì)象,并分布到單個(gè)對(duì)象中。
CLIENTS_RECEIVE_MARKETING_VIA: {
0: {
CLIENTS_ISMARKETINGVIAEMAIL: false,
},
1: {
CLIENTS_ISMARKETINGVIAMAIL: false,
},
2: {
CLIENTS_ISMARKETINGVIAPHONE: false,
},
3: {
CLIENTS_ISMARKETINGVIASMS: {
0: {
CLIENTS_ISMARKETINGVIATEXT: false,
},
1: {
CLIENTS_ISMARKETINGVIAPIC: false,
},
},
},
},
會(huì)輸出
{
CLIENTS_ISMARKETINGVIAEMAIL: false,
CLIENTS_ISMARKETINGVIAMAIL: false,
CLIENTS_ISMARKETINGVIAPHONE: false,
CLIENTS_ISMARKETINGVIATEXT: false,
CLIENTS_ISMARKETINGVIAPIC: false,
}
添加回答
舉報(bào)