如何提取高度嵌套的对象里的指定属性?
function findKey(data, field) {
let finding = "";
for (const key in data) {
if (key === field) {
finding = data[key];
}
if (typeof data[key] === "object") {
finding = findKey(data[key], field);
}
if (finding) {
return finding;
}
}
return null;
}
//测试
console.log(
findKey(
{
name: "zhangsan",
age: 19,
stuInfo: {
stuNo: 1,
classNo: 2,
score: {
htmlScore: 100,
cssScore: 90,
jsScore: 94,
},
},
},
"cssScore"
)
);