js递归去除数组对象里面的type
时间: 2023-04-01 22:00:22 浏览: 62
可以使用递归函数来遍历数组对象,判断每个元素是否为对象,如果是则继续递归遍历,直到找到不是对象的元素,然后判断该元素是否有 type 属性,如果有则删除该属性。以下是示例代码:
function removeType(obj) {
if (Array.isArray(obj)) {
obj.forEach((item) => {
removeType(item);
});
} else if (typeof obj === "object" && obj !== null) {
Object.keys(obj).forEach((key) => {
removeType(obj[key]);
});
if (obj.hasOwnProperty("type")) {
delete obj.type;
}
}
}
const arr = [
{ type: "a", name: "obj1" },
{ type: "b", name: "obj2" },
{ type: "c", name: "obj3", subObj: { type: "d", name: "obj4" } },
"not an object",
];
removeType(arr);
console.log(arr); // [{name: "obj1"}, {name: "obj2"}, {name: "obj3", subObj: {name: "obj4"}}, "not an object"]