简体   繁体   中英

JavaScript Object retrieve value dynamically

Sorry if it sounds like a stupid question

I have this following JavaScript object:

data = {
    "Max" : 100
}

This same object can also have the following form:

data = {
    "January": {"Max" : 100}
}

I want to use one same function to retrieve the value of Max if given the two forms

And it made me wonder if it is possible to write a conditional expressions directly in the [] when you write the values you want to retrieve? Is this following expression allowed in JavaScript? Something like this:

data[monthly ? 'month' : '']

Of course I tried it and it doesn't work. But is there another way to do such a thing in a line? monthly is a boolean

You can use the following script to do that, I have added some comments to make it clear

 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));

You can make use of 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));

There's yet another way of achieving this using Array.find and 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM