[英]I want to initialize an array of objects in javascript
when I click new button, I have to clear all information like this.当我点击新按钮时,我必须清除所有这样的信息。 from
从
testInfo:{
test1: 12
test2: "test2"
...
test99: "test99"
}
to到
testInfo:{
test1: 0 (or "")
test2: ""
...
test99: ""
}
any good idea?有什么好主意吗? thanks.
谢谢。
for (const key in testInfo) {
testInfo[key] = typeof testInfo[key] === 'number' ? 0 : '';
}
You may try creating an object from mapped entries like so:您可以尝试从映射条目创建一个对象,如下所示:
const testInfo = { test1: 12, test2: "test2", test99: "test99", } console.log(Object.fromEntries(Object.keys(testInfo).map(key => [key, ""])));
const toReset = testInfo =>
Object.fromEntries(Object.keys(testInfo).map(key => [key, '']));
setState({ testInfo: toReset(someState) });
The question uses object syntax, but I think you might want an array.该问题使用对象语法,但我认为您可能需要一个数组。
And if you need pre-created integer properties then you can do this:如果您需要预先创建的整数属性,那么您可以这样做:
const a = [...Array(99)] // 99 / whatever console.log(JSON.stringify(a))
And if you really don't want an array:如果你真的不想要一个数组:
const o = {...[...Array(99)]} // 99 / whatever console.log(o)
If the object is not part of your React state:如果对象不是你的 React 状态的一部分:
// Initialize const testInfo = { test1: 12, test2: "test2", test99: "test99" }; // Update for (const key in testInfo) { testInfo[key] = ""; } console.log(testInfo);
If the object is part of your React state then you always need to create a fresh object from scratch, and set that as the new state.如果对象是你的 React 状态的一部分,那么你总是需要从头开始创建一个新对象,并将其设置为新状态。
Example using React Hooks :使用React Hooks 的示例:
// Initialize
const [testInfo, setTestInfo] = useState({ test1: 12, test2: "test2", test99: "test99" });
// Update
const newInfo = testInfo.clone();
for (const key in newInfo) {
newInfo[key] = "";
}
setTestInfo(newInfo);
Keep a state for your formInfo and a default state value in a constant.保持 formInfo 的状态和常量中的默认状态值。
const defaultTestInfo = {
test1: 0,
test2: "",
test99: "",
}
const resetFormInfo = () => {
this.setState({ testInfo: defaultTestInfo })
}
And pass resetFormInfo
in your button onClick
并在您的按钮
onClick
传递resetFormInfo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.