将字符串转换为对象数组

将字符串转换为对象数组

本文介绍了将字符串转换为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以 HHMM-HHMM\nHHMM\nHHMM格式(小时和分钟)的文本区域字符串开头。所需的输出是一组对象,这些对象键入第一个数字作为开头:第二个数字作为结束,例如:

I'm starting with a text-area string in "HHMM-HHMM\nHHMM\nHHMM" format (hours and minutes). The desired output is an array of objects that key the 1st number to start: and the 2nd to end, like:

[
  {
    start: 0900,
    end: 1000
  },
  {
    start: 1200,
    end: 1300
  },
]

在下面的代码中,我按行分割了初始字符串,以便它们将显示为数组:

In the code below I have split the initial string by line so that they will appear as an array:

splitting_array = ["0900-1000", "1200-1300"]

接下来,我尝试使用array.map将每个字符串映射到映射到start和end属性的新对象数组。我的挂断在这里,我可以使用连字符拆分第一和第二个数字,但是我不知道如何从那里进行对象属性映射(开始:和结束:)。

Next I am trying to use array.map to map each string to a new array of objects mapped to start and end properties. My hangup is here, I can split the 1st and second number using the hypen but I do not know how to do the object property mappings (start: and end:) from there. Thanks for any suggestions.

var free_time_hours = document.getElementById('ftid')
  free_time_hours.addEventListener("blur", save_free_time_hours)

function save_free_time_hours () {

  // todo: break the new lines into array elements. Reset each time in case the user input updates

  var splitting_array = free_time_hours.value.split(/\n/)

  // todo: use the map function to map each string to an object with start and end properties

  var split_objects = splitting_array.map(function(str) {
    var box = str.split('-') // box[0] = 1200, box[1] = 1300
    var obj = {}
  // stuck here

  })

  // console.log("objectified start/end values")
  // console.log(split_objects)

}


推荐答案

所以 String.split 返回一个由(但不包括)您传入的是分割字符串,所以 box [0] 是您的开始,而 box [1] 是您的开始结束。然后,您只需要返回要映射到字符串项目的对象即可。

So String.split returns an array of your strings split by (and not including) the split-string you pass in, so box[0] is your start, and box[1] would be your end. Then, you just need to return the object that is to be mapped to your string item.

var splitting_array = ["0900-1000", "1200-1300"];
var split_objects = splitting_array.map(function(str) {
  var box = str.split('-');
  return {start: box[0], end: box[1]}
});
console.log(split_objects); // [{start:"0900", end:"1000"}, {start:"1200", end:"1300"}]

这篇关于将字符串转换为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:54