Javascript 如何重命名对象键&;将对象值从字符串更改为数字
好的,伙计们 我正在处理来自Javascript 如何重命名对象键&;将对象值从字符串更改为数字,javascript,reactjs,Javascript,Reactjs,好的,伙计们 我正在处理来自React的第三方库,希望操纵状态,以便以后可以将这种新的代码格式推送到新的对象中 当我使用这个库以一个值为目标时,无论我何时选择,我的状态都是这样的字符串-例如,如果我选择20:30,this.state.time等于“20:30” 我想将这个字符串处理成如下对象: 从“20:30”到时间:{hour:20,minutes:30}///小时和分钟现在都是数字 我的完整代码如下: import React from "react"; import TimePicker
React
的
第三方库,希望操纵状态,以便以后可以将这种新的代码格式推送到新的对象中
当我使用这个库以一个值为目标时,无论我何时选择,我的状态都是这样的字符串-例如,如果我选择20:30,this.state.time
等于“20:30”
我想将这个字符串
处理成如下对象:
从“20:30”
到时间:{hour:20,minutes:30}
///小时和分钟现在都是数字
我的完整代码如下:
import React from "react";
import TimePicker from "react-time-picker";
import './Clock.css'
class Clock extends React.Component {
state = {
time: '0:00',
pushTime: [],
value: ''
};
onChangeTimePickerHandler = time => {
this.setState({time});
let currentTime = this.state.time;
this.props.CallbackRenderTime(currentTime)
};
//I am using TimePicker library for React and want to manipulate the income from the chosen time
pushNewTimeHandler = () => {
let time = [...this.state.time] ;// ["1", "0", ":", "0", "0"]
time.splice(2, 1);
let timeToOneString = time.join().replace(/,/g, "");
let prepareStringForNewObject = (value, index) => {
let array = value.substring(0,index) + ',' + value.substring(index);
return array.split(',')
};
let newObj = {...prepareStringForNewObject(timeToOneString,2)};
console.log(newObj); // {0: "10", 1: "00"}
};
render() {
return (
<div>
<TimePicker
onChange={this.onChangeTimePickerHandler}
value={this.state.time}/>
<button onClick={this.pushNewTimeHandler}>Push the Array of Time</button>
<p>{this.state.time}</p>
</div>
)
}
}
export default Clock
因此,在我丑陋的解决方案pushNewTimeHandler
中,我仍然需要将对象键重命名为hour
和minutes
,还需要将小时和分钟的字符串值转换为数字。我将时间字符串拆分为:
,创建一个字符串数组,然后将每个字符串映射到一个数字,并将结构分解为=
左侧的小时和分钟。然后,您可以创建小时
和分钟
的对象:
const str='20:30';
const[hour,minutes]=str.split(“:”).map(Number);
const obj={小时,分钟};
控制台日志(obj)代码>
//I am using TimePicker library for React and want to manipulate the income from the chosen time
manipulateTimeHandler = () => {
//this.state.time is "10:00"
let time = [...this.state.time] ;// now it looks like this: ["1", "0", ":", "0", "0"]
time.splice(2, 1);
let timeToOneString = time.join().replace(/,/g, "");
let prepareStringForNewObject = (value, index) => {
let array = value.substring(0,index) + ',' + value.substring(index);
return array.split(',')
};
let newObj = {...prepareStringForNewObject(timeToOneString,2)};
console.log(newObj); //finally it became the object, but the object values are still
//strings and the object keys still need to be changed into "hour"
//and "minutes" {0: "10", 1: "00"}
};