[英]I want to initialize an array of objects in javascript
當我點擊新按鈕時,我必須清除所有這樣的信息。 從
testInfo:{
test1: 12
test2: "test2"
...
test99: "test99"
}
到
testInfo:{
test1: 0 (or "")
test2: ""
...
test99: ""
}
有什么好主意嗎? 謝謝。
for (const key in testInfo) {
testInfo[key] = typeof testInfo[key] === 'number' ? 0 : '';
}
您可以嘗試從映射條目創建一個對象,如下所示:
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) });
該問題使用對象語法,但我認為您可能需要一個數組。
如果您需要預先創建的整數屬性,那么您可以這樣做:
const a = [...Array(99)] // 99 / whatever console.log(JSON.stringify(a))
如果你真的不想要一個數組:
const o = {...[...Array(99)]} // 99 / whatever console.log(o)
如果對象不是你的 React 狀態的一部分:
// Initialize const testInfo = { test1: 12, test2: "test2", test99: "test99" }; // Update for (const key in testInfo) { testInfo[key] = ""; } console.log(testInfo);
如果對象是你的 React 狀態的一部分,那么你總是需要從頭開始創建一個新對象,並將其設置為新狀態。
使用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);
保持 formInfo 的狀態和常量中的默認狀態值。
const defaultTestInfo = {
test1: 0,
test2: "",
test99: "",
}
const resetFormInfo = () => {
this.setState({ testInfo: defaultTestInfo })
}
並在您的按鈕onClick
傳遞resetFormInfo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.