简体   繁体   English

我想从数组中的 object 获取值键

[英]I want to get values key from object which is in array

I have an array of days我有很多天

"selectedDays": [
            "Sunday",
            "Tuesday",
            "Wednesday"
        ]

This is coming request body, Now I have to map and generate the number of it so I have one object这是即将到来的请求正文,现在我必须 map 并生成它的数量,所以我有一个 object

const Week_mapping = {
  "Sunday": 0,
  "Monday": 1,
  "Tuesday":2,
  "wednesday":3,
  "Thursday": 4,
  "Friday": 5,
  "Saturday": 6
}

Example-1 - Suppose array has Sunday, Tuesday, Wednesday.示例 1 - 假设数组有星期日、星期二、星期三。

Desired Output:所需的 Output:

[0,2,3]

Example-2 - Suppose array has Sunday, Monday,Tuesday, Wednesday, Friday示例 2 - 假设数组有星期日、星期一、星期二、星期三、星期五

Desired Output:所需的 Output:

[0,1,2,3,5]

How can I achieve this?我怎样才能做到这一点?

You could do it as follows using simple maps() -您可以使用简单的maps()执行以下操作 -

 const Week_mapping = { "Sunday": 0, "Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4, "Friday": 5, "Saturday": 6 } const selectedDays = [ "Sunday", "Tuesday", "Wednesday" ] // The following line will return array in which the elements in // selectedDays list will be mapped to their corresponding Week_mapping const res = selectedDays.map(element => Week_mapping[element]) console.log(res)

You can read more about maps here if you aren't already aware about them.如果您还不了解地图,可以在此处阅读有关地图的更多信息。 Basically, the map() takes an function and maps each element of array(on which map is used) to the result returned by the function.基本上, map()采用 function 并将数组的每个元素(使用 map)映射到 function 返回的结果。

So, the above code can also be written in following way =>所以,上面的代码也可以这样写=>

 const Week_mapping = { "Sunday": 0, "Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4, "Friday": 5, "Saturday": 6 } const selectedDays = [ "Sunday", "Tuesday", "Wednesday" ] // The following function will take a week day and return the number corresponding to it function weekDaysToNumMappings (weekDay){ return Week_mapping[weekDay]; } // Now, we map each element from selectedDays to value returned by above function const res = selectedDays.map(weekDaysToNumMappings) console.log(res)

Hope this helps !希望这可以帮助 !

This will check if no days are selected:这将检查是否没有选择日期:

let answer = selectedDays && selectedDays.length ? 
             selectedDays.map(key => Week_mapping[key]) 
            : []

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

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