helloWorld
helloWorld

Reputation: 153

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.

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.

I have two questions:

  1. Is there a more elegant way to instantiate this?

  2. How would I do this using the Object.entries method?

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!

Upvotes: 3

Views: 6102

Answers (2)

Sahil Lamba
Sahil Lamba

Reputation: 106

To answer your questions -

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

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

Upvotes: 2

Abito Prakash
Abito Prakash

Reputation: 4770

If you need to set all the values in the object to true, you can do something like this

Object.keys(obj).forEach(key => obj[key] = true);

Object.keys will return all the keys in that object in an array. By looping over that array and then using obj[key] we can access each key of the object and set it to true

Upvotes: 5

Related Questions