[英]React/JSX: Iterating through an object with key/value pairs
I have an object that I'm using to keep track of which checkboxes have been checked on a UI.我有一个对象,我用它来跟踪在 UI 上选中了哪些复选框。
It looks something like this:它看起来像这样:
checked: { key1: false, key2: false, key3: false, key4: false, key5: false, key6: false, key7: false, key8: false, key9: false, key10: false },
I need to be able iterate through this object and set certain values to true/false, depending on the behavior the user wants from the UI.我需要能够遍历此对象并将某些值设置为 true/false,具体取决于用户希望从 UI 获得的行为。
I have two questions:我有两个问题:
Is there a more elegant way to instantiate this?有没有更优雅的方法来实例化它?
How would I do this using the Object.entries method?我将如何使用 Object.entries 方法来做到这一点?
I'd like to do something like this, but it doesn't work:我想做这样的事情,但它不起作用:
let obj = {k1: false, k2: false, k3: false}
Object.entries(obj).forEach(([key, value]) => {
obj.value = true;
console.log(`${key} ${value}`);
});
Thank you!谢谢!
If you need to set all the values in the object to true, you can do something like this如果您需要将对象中的所有值都设置为 true,您可以这样做
Object.keys(obj).forEach(key => obj[key] = true);
Object.keys
will return all the keys in that object in an array. Object.keys
将在数组中返回该对象中的所有键。 By looping over that array and then using obj[key]
we can access each key of the object and set it to true通过循环遍历该数组然后使用
obj[key]
我们可以访问对象的每个键并将其设置为 true
To answer your questions -回答你的问题——
This is a pretty good way to store multiple checked booleans, as you can access them using object destructuring like const { key1, key2, ... } = checked
which, IMHO makes the code more readable.这是存储多个检查布尔值的一种很好的方法,因为您可以使用对象解构访问它们,例如
const { key1, key2, ... } = checked
which,恕我直言,使代码更具可读性。
Try -尝试 -
Object.entries(obj).forEach([key, value] => {
// Set obj key/value
obj[key] = true // or use value here
})
Refer -参考 -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.