简体   繁体   English

JavaScript 对象动态检索值

[英]JavaScript Object retrieve value dynamically

Sorry if it sounds like a stupid question对不起,如果这听起来像一个愚蠢的问题

I have this following JavaScript object:我有以下 JavaScript 对象:

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如果给定两种形式,我想使用一个相同的function来检索Max的值

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? 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 monthly是一个布尔值

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您可以使用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 .还有另一种使用Array.findOptional 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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