如何在ES6中格式化数组数据

时间:2018-09-24 05:19:11

标签: reactjs ecmascript-6

如何格式化要插入到数据库中的数组值?

I want the values inserted similar to the one with yellow underline

当我尝试在视图上显示值时,

when I tried showing the values on my view,

我提交的代码

onSubmit(values) {
    const { mutate, createArea, center } = this.props;
    const data = {
      name: values.name,
      address: values.address,
      days_of_availability: String(values.days_of_availability),
      time_schedule: values.time_schedule.toString(),
      notes: values.notes,
      partnership: values.partnership,
      promotional_ads: values.promotional_ads,
      date_period: values.date_period,
      days: values.days.join(" - "),
      start_time: values.start_time,
      end_time: values.end_time,
      lat: values.lat,
      long: values.long,
      //lat: center.lat.toString(),
      //long: center.lng.toString(),
    }
    createArea(mutate, data)
  }

根据我的表单

class AreaForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      daysAvailability: false,
      timeSched: false,
      data: {},
      days: [
        { name: 'Monday' },
        { name: 'Tuesday' },
        { name: 'Wednesday' },
        { name: 'Thursday' },
        { name: 'Friday' },
        { name: 'Saturday' },
        { name: 'Sunday'}
      ],
    }

    this.onToggleDays = this.onToggleDays.bind(this);
    this.onToggleSched = this.onToggleSched.bind(this);
  }

我如何能够插入类似于上面屏幕截图中下划线所示的值。我尝试了.join(“-”),但第二个屏幕截图显示了输出,但仍显示[“和”]。

1 个答案:

答案 0 :(得分:2)

您从数据库得到的响应是string而不是array,因此join方法没有用。

如果您只需要从作为响应得到的字符串中删除[""],请使用以下方法:

formattedString = marker.days.substr(2) //removes first 2 characters from the string

现在也使用切片方法通过删除最后2个字符来分配字符串

days: formattedString.slice(0,-2) //slices last 2 characters from the string

您也可以同时执行以下两项操作:

days: marker.days.slice(2,-2)