我想从数组中的对象获取值键

时间:2020-07-09 18:55:04

标签: javascript node.js arrays reactjs object

我有很多天

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

这是即将到来的请求正文,现在我必须映射并生成它的编号 所以我只有一个物体

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

示例1 -假设数组具有星期日,星期二,星期三。

所需的输出:

[0,2,3]

示例2 -假设数组具有星期日,星期一,星期二,星期三,星期五

所需的输出:

[0,1,2,3,5]

我该如何实现?

2 个答案:

答案 0 :(得分:0)

您可以使用简单的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)

如果您还不了解地图here,则可以了解更多信息。基本上,map()会使用一个函数,并将array的每个元素(在其上使用了映射)映射到该函数返回的结果。

因此,上面的代码也可以按以下方式编写=>

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)

希望这会有所帮助!

答案 1 :(得分:0)

这将检查是否未选择日期:

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