在这里插入代码片<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><style>.test {border-width: 20px;width: 0;height: 0;border-color: transparent, green, transparent, transparent;}</style><body><div class="trignale"><script>const obj = {a: {d: { e: 5 },},c: 3,};function flatten(obj) {let res = {};function detail(obj, oldKey = "") {let sonObj = {};for (let key in obj) {let keyStr = `${oldKey ? oldKey + "." : ""}${key}`;if (obj.hasOwnProperty(key)) {console.log(typeof obj[key]);if (typeof obj[key] != "object") {sonObj[keyStr] = obj[key];console.log(res, "RES1");res = { ...res, ...sonObj };console.log(res, "RES2");} else {console.log(res, "res1");let b = detail(obj[key], keyStr);res = { ...res, ...b };console.log(res, "res2");}}}console.log(sonObj, "sonObj");return sonObj;}detail(obj);console.log(res);return res;}flatten(obj);sonObj</script></div></body>
</html>
function flatten(obj) {let res = {};function detail(obj, oldKey = "") {if (Array.isArray(obj)) {obj.forEach((item, index) => {const keyStr = `${oldKey}[${index}]`;if (typeof item !== "object" || item === null) {res[keyStr] = item;} else {detail(item, keyStr);}});} else if (typeof obj === "object" && obj !== null) {for (let key in obj) {if (obj.hasOwnProperty(key)) {const keyStr = `${oldKey ? oldKey + "." : ""}${key}`;if (typeof obj[key] !== "object" || obj[key] === null) {res[keyStr] = obj[key];} else {detail(obj[key], keyStr);}}}}}detail(obj);return res;
}
const objWithArray = {a: {b: 1,c: 2,d: { e: 5 },},b: [1, 3, { a: 2, b: 3 }],c: 3,
};console.log(flatten(objWithArray));