简体   繁体   中英

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:

 // 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.

Example using 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.

const defaultTestInfo = {
      test1: 0,
      test2: "",
      test99: "",
    }

const resetFormInfo = () => {
  this.setState({ testInfo: defaultTestInfo })
}

And pass resetFormInfo in your button onClick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM