简体   繁体   中英

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

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.

Desired Output:

[0,2,3]

Example-2 - Suppose array has Sunday, Monday,Tuesday, Wednesday, Friday

Desired Output:

[0,1,2,3,5]

How can I achieve this?

You could do it as follows using simple 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.

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]) 
            : []

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