抱歉,这听起来像是一个愚蠢的问题
我有以下JavaScript对象:
data = {
"Max" : 100
}
同一对象也可以具有以下形式:
data = {
"January": {"Max" : 100}
}
如果要使用两种形式,我想使用相同的function
来检索Max
的值
这让我想知道,当您编写要检索的值时,是否可以直接在[]
中编写条件表达式? JavaScript中是否允许以下表达式?像这样:
data[monthly ? 'month' : '']
我当然尝试过,但是它不起作用。但是,有没有另一种方法可以做到这一点呢? monthly
是布尔值
答案 0 :(得分:2)
您可以使用以下脚本来执行此操作,我添加了一些注释以使其清晰
var data1 = {
"Max" : 100
}
var data2 = {
"January": {"Max" : 100}
}
// storing the months in an array to loop over and see if the current key is a month
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function getMax(data) {
// if the key `Max` exists in data then just get the value of `data.Max` else loop over the months, and see if one of the months is a key and stores a truthy value, in this case it stores an object, so that's what we want and then get it's .Max value
return "Max" in data ? data.Max : data[months.filter(m => data[m] ? m : "")[0]].Max;
}
console.log(getMax(data1));
console.log(getMax(data2));
答案 1 :(得分:0)
您可以使用Object.values
let data = {
"Max": 100
};
const getMax = (data) => {
//check if "Max" is available in the `data`, if so return `data.Max` else
//get values of the keys in the object using `Object.values` and
//retreive `Max` from the array
return data.Max ? data.Max : Object.values(data)[0].Max
}
console.log(getMax(data));
data = {
"January": {
"Max": 200
}
}
console.log(getMax(data));
还有另一种使用Array.find
和Optional Chaining
来实现这一目标的方法。
let data = {
Max: 100,
};
const getMax = (data = {}) => {
return data.Max ? data.Max : Object.values(data).find(({ Max }) => Max)?.Max;
};
console.log(getMax(data));
data = {
January: { Max: 200 },
};
console.log(getMax(data));