我有一个具有多个嵌套的对象。每个对象都有自己的键、iq、name、total。例如,需要找到 iq 的最大值和最小值。关键 child 可能是也可能不是。
let infoList= {
name: Jone,
iq: 130,
children: [{
name: Joy,
iq: 121,
children: [{
name: Ross,
iq: 110,
children: [{
....
}]
}]
}]
}
最佳答案
这是一个递归解决方案。请注意,我将名称更改为字符串。
let infoList= {
name: 'Jone',
iq: 130,
children: [{
name: 'Joy',
iq: 121,
children: [{
name: 'Ross',
iq: 110,
children: [{ name: 'Joe', iq: 20 }]
}]
}]
}
function ancestorIQs(person) {
let arr = [person.iq];
if (!person.children) return arr;
return person.children.reduce(function (iqs, child) {
return iqs.concat(ancestorIQs(child));
}, arr);
}
let result = ancestorIQs(infoList);
console.log(Math.min(...result)); // 20
console.log(Math.max(...result)); // 130
关于javascript - 查找最小值和最大值键嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53388995/