Change a single value from an array of objects after iterating in javaScript

foreach javascript
change value in array javascript
javascript update object in array es6
javascript map
javascript update object property in array
javascript foreach object
javascript loop through array of objects
change value in array python

Here is my code:

let user = [
    {id: 1, name: "Chris", active: "true"},
    {id: 2, name: "James", active: "true"},
    {id: 3, name: "Jeremy", active: "true"},
];

handleClick = () => {
    for(let i in user) {
        if (Object.hasOwnProperty.call(user, i)) {
                user[i].active = false;
         }
    }
};

Hi.

I've been looking over many topics but i don't find any answers to my question.

As you can see on a click (handleClick) I want to modify the status of active to "true" to "false" and vice versa. But I want that this happen only on the user that I click, not all of the them. Each user has his own button.

I start to think that maybe I should use the id somehow.

Use ES6 to handle this function also if you trying to use boolean you should write true or false without quotation or double-quotation

let user = [{
    id: 1,
    name: "Chris",
    active: true
  },
  {
    id: 2,
    name: "James",
    active: true
  },
  {
    id: 3,
    name: "Jeremy",
    active: true
  },
];

function handleClick(id) { // handleClick = (id) => {
  const result = user.map(obj =>
    obj.id === id ? { ...obj,
      active: !obj.active
    } : obj
  )
  console.log(result)
}
<div onclick="handleClick(1)">Click</div>

<!-- React version -> <div onClick="this.handleClick(id)">Click</div> -->

How to change value of object which is inside an array using , It basically stores different elements in one box and can be later assesssed with the variable. This method adds items to the end of an array and changes the original array. If the second parameter is not declared, every element starting from the given This method is good for iterating through an array. One of the most popular methods of iterating through datasets in JavaScript is the .map() method. .map() creates an array from calling a specific function on each item in the parent array. .map() is a non-mutating method that creates a new array inste

Here is the solution:

let user = [
    {id: 1, name: "Chris", active: "true"},
    {id: 2, name: "James", active: "true"},
    {id: 3, name: "Jeremy", active: "true"},
];

handleClick = id => {
    user.forEach( obj => {
      if(obj.id === id) 
     obj.active = !obj.active;
    });
};

How to Manipulate Arrays in JavaScript, One thing I had not shown, is about second argument of the forEach(). You can pass an object - in this case, an array -, that will be the `this` inside the forEach The `map()` method works like `forEach()`: this method iterates by an array, and Accessing an Object's Keys, Values, and Entries in JavaScript. The reduce() method runs a function on each array element to produce (reduce it to) a single value. The reduce() method works from left-to-right in the array. See also reduceRight() .

I saw you used a reactjs so what you are looking for is something like this:

handleClick = id => {
  let arr = this.state.users.map(user => {
    let u = { ...user };

    if(u.id === id) {
      u.active = !u.active;
    }

    return u;
  });

  this.setState({ users: arr });
}

Check out this demo:

let users = [
  {id: 1, name: "Chris", active: true}, 
  {id: 2, name: "James", active: false}, 
  {id: 3, name: "Jeremy", active: true}
];

class Demo extends React.Component {
    state = { users };
    
    colorize = active => active ? 'green' : 'red';
    
    handleClick = id => {
      let arr = this.state.users.map(user => {
        let u = { ...user };
        
        if(u.id === id) {
          u.active = !u.active;
        }
        
        return u;
      })
      
      this.setState({ users: arr });
    }
    
    render (){
        return (
         <div>
           {this.state.users.map(user => (
            <div key={user.id} className="row">
              <p className="user">{user.name}</p>
              <p className={`status ${this.colorize(user.active)}`}>
                {user.active.toString()}
              </p>
              <button 
                onClick={() => this.handleClick(user.id)}>
                Change status
              </button>
            </div>
           ))}
         </div>
        );
    }
}
ReactDOM.render(<Demo />, document.getElementById('app'));
.row {
  display: flex;
  flex-direction: row;
}

.user {
  font-weight: bold;
}

.user::after {
  content: ":";
}

.status {
  margin-left: 10px;
}

button {
  margin: 15px 5px 5px 5px;
  border-radius: 10px;
}

.red { 
  color: red;
}

.green {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Replace your loops by Array methods - map(), JavaScript has multiple iteration methods, starting with a traditional for loop and to loop over arrays in JavaScript, but it can be difficult choosing the right one. how to use associative arrays or objects to find the values you want. The following is an example of using JavaScript to loop through an array. Creating objects in JavaScript (4 Different Ways) Ways to implement Object.values() in JavaScript; How to compare two JavaScript array objects using jQuery/JavaScript ? How to move an array element from one array position to another in JavaScript? Difference between array.size() and array.length in JavaScript

Pass in the ID of the user in the function then add a if statement

(id) =>{ user.forEach( obj =>{
 If(obj.id === id) 
obj.active = !obj.active;
})} 

Looping JavaScript Arrays Using for, forEach & More , In these cases, you'll want to use a while loop and test the array elements: To create this in JavaScript using a multidimensional array, use the following code: In the code, when the value of one of the objects in the first array is changed,� This makes sense if you understand each JavaScript object is an associative array. When you think about a JavaScript in terms of an associative array the index is the member name. obj["property-name"] This returns a reference to the value, which could be a traditional value, function, array or a child object.

5. Working with Arrays and Loops, forEach() in JavaScript calls the provided function on each array item with like correct handling of this and how to iterate array-like objects. following example in a browser, and pay attention to the value of this : Inside the callback of forEach() , this points also to an instance of Unique . Edit on GitHub� Introduction. An object in JavaScript is a data type that is composed of a collection of names or keys and values, represented in name:value pairs.The name:value pairs can consist of properties that may contain any data type — including strings, numbers, and Booleans — as well as methods, which are functions contained within an object.

How to Use forEach() to Iterate an Array in JavaScript, We could get creative with strings—after all, strings can have any length, so we You can change their properties, causing a single object value to have different This kind of loop is common in classical JavaScript—going over arrays one� A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it. In the user object, there are two properties: The first property has the name "name" and the value "John". The second one has the name "age" and the value 30.

Data Structures: Objects and Arrays :: Eloquent JavaScript, One of the most popular methods of iterating through datasets in a new array as opposed to mutating methods, which only make changes to the calling array. rendering lists in JavaScript libraries, and reformatting array objects. and an important parameter of that function is the current value of the item� I would agree here, were it not for ECMA-262 defining an array as an object having a forEach(), map(), reduce(), filter(), which all take callbacks receiving the order [value, index, array]. An object in JS can be understood as just another collection; and then these methods become unified in their parameters of [value, key|index, context

Comments
  • Is this from a ReactJS app ? How is the handleClick function called ?
  • Yes it is sir :) But i don't want to put the whole thing. I prefer to start from JS and then adapt.
  • I've asked that because it matters how the elements in the user array are associated with the DOM elements.
  • Ok i see ! Let me make some order in my code and drop what is needed :)
  • Please post a working example using a code snippet or jsfiddle.
  • @JeremyBertin Glad to help, please select the best answer that solved your problem as accepted answer or +1 up vote! (It's your choice!)
  • Thanks for your help :) Problem have been solved already but it's always nice to have a different approach.
  • Damn. This looks great ! Gone try this right away :)
  • @JeremyBertin glad I could help!