我有下面的对象,可以有很多职业水平(我现在已经显示了2个):
var input =
{
"careerLevel": "Associate",
"careerLevels": [
{
"201609": 21,
"201610": 22,
"201611": 23,
"careerID": "10000120"
},
{
"201609": 31,
"201610": 32,
"201611": 33,
"careerID": "10000130"
}]
};
我想检查 careerID 属性,我需要提取具有 careerID 值最高的元素。 因此,在这种情况下,输出将如下所示:
var output= {"201609": 31,
"201610": 32,
"201611": 33}
我的尝试如下:
var res = Math.max.apply(Math, oldArr.careerLevels.map(function (o) { return o.careerID; })) // This gives me the highest careerID value
var highestOrderArr = oldArr.careerLevels.filter(element => {
// i think here i need to make a check for the comparison
});
答案 0 :(得分:1)
另一种方法是排序并获取最后一个对象。
var input = { "careerLevel": "Associate", "careerLevels": [{ "201609": 21, "201610": 22, "201611": 23, "careerID": "10000120" }, { "201609": 31, "201610": 32, "201611": 33, "careerID": "10000130" } ]},
highest = input.careerLevels.sort((a, b) => a.careerID - b.careerID).pop();
console.log(highest);

.as-console-wrapper { max-height: 100% !important; top: 0; }

使用函数reduce
var input = { "careerLevel": "Associate", "careerLevels": [{ "201609": 21, "201610": 22, "201611": 23, "careerID": "10000120" }, { "201609": 31, "201610": 32, "201611": 33, "careerID": "10000130" } ]},
highest = input.careerLevels.reduce((a, c) => c.careerID > a.careerID ? c : a, {careerID: Number.MIN_SAFE_INTEGER});
console.log(highest);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)
我们可以使用reduce来获得最高careerID
并输出该对象。
var input ={
"careerLevel": "Associate",
"careerLevels": [
{
"201609": 21,
"201610": 22,
"201611": 23,
"careerID": "10000120"
},
{
"201609": 31,
"201610": 32,
"201611": 33,
"careerID": "10000130"
}]
};
const out = input.careerLevels.reduce((prev, current) => {
return (prev.careerID > current.careerID) ? prev : current
}, false)
console.log(out);