2 回答
TA贡献1853条经验 获得超9个赞
有趣的递归问题。
但源数据有点奇怪。数组项不是键值对象。
应该是这样的:
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贡献1836条经验 获得超3个赞
该函数递归地将对象的对象合并为单个对象,但成本太高。
时间复杂度约为O(n 2 log n)
(虽然没有测试其他输入,所以让我知道它是否不适用于所有内容)
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 };
}
});
});
}
例子
输出将始终是每次迭代中最内部的对象,并分布到单个对象中。
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,
},
},
},
},
会输出
{
CLIENTS_ISMARKETINGVIAEMAIL: false,
CLIENTS_ISMARKETINGVIAMAIL: false,
CLIENTS_ISMARKETINGVIAPHONE: false,
CLIENTS_ISMARKETINGVIATEXT: false,
CLIENTS_ISMARKETINGVIAPIC: false,
}
添加回答
举报