使用 Object.entires()andisArray检查它是否是一个数组
obj = {
name: "jane",
age: 22,
interested_books: [
{ book_name: "xxx", author_name: "yyy" },
{ book_name: "aaa", author_name: "zzz" },
],
hobbies: ["reading", "football"],
address: { street_name: "dace street", door_no: 12 },
};
function getArrWithOb(obj) {
return Object.fromEntries(
Object.entries(obj).filter((o) => {
if (Array.isArray(o[1])) {
if (o[1].every((ob) => typeof ob == "object")) {
return o;
}
}
})
);
}
console.log(getArrWithOb(obj));
从评论看来你想要返回的是你可以使用的属性的名称reduce
obj = { name: "jane", age: 22, interested_books: [ { book_name: "xxx", author_name: "yyy" }, { book_name: "aaa", author_name: "zzz" }, ], hobbies: ["reading", "football"], address: { street_name: "dace street", door_no: 12 }, };
function getArrWithOb(obj) {
return Object.entries(obj).reduce((r, o) => {
if (Array.isArray(o[1])) {
if (o[1].every((ob) => typeof ob == "object")) {
r.push(o[0]);
}
}
return r;
}, []);
}
console.log(getArrWithOb(obj));