updating array in object properties

javascript update object in array es6
find and update object in array javascript
javascript update object property in array es6
replace object in array javascript
javascript array of objects
javascript convert array to object with keys
change value of key in object javascript
typescript modify object

I have an object defined like this:

import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor() {
    super();
    this.state = {
    lists: ["Dogs", "Cats"],
    items: {Dogs:[], Cats:[]}
    };
  }

  handleAddItem(item) {
    console.log(this.props.idName);
    console.log(item);
  }

I have the variable

console.log(this.props.idName)// output: Dogs
console.log(item);// output {name: "lofi"}  

I don't know how to update the object items{} to make it becоme like this:

items{Dogs:[{name: "lofi"}], Cats:[]}

To update a nested Array substate, you can use the spread operator to append elements

handleAddItem = item => {
  this.setState((prevState, props) => ({
    items: {
      ...prevState.items,
      [props.idName]: [
        ...prevState.items[props.idName],
        item
      ]
    }
  }))
}

How to change value of object which is inside an array using , objIndex = myArray.findIndex((obj => obj.id == 1)); //Log object to Console. console.log("Before update: ", myArray[objIndex]) //Update object's name property. I am trying to write a basic function that will decide whether the object already exists in array of objects based on unique id that is inside this object as a property. Upon searching I came up with this code, and it seems to be doing the job fine, but I can imagine there is a better and faster way to determine whether to push or update the

Useful Javascript Array and Object Methods, With all these array and object methods you'll find you never have to reach for a things likes flattening an array of arrays, grouping objects by a property, and think const does, however const allows you to modify an object. Updating objects in loops. With value types, the only way to update the array is to use a for loop because we need to know the index to replace the value. We have more options with objects because they are reference types. Here is a quick example:

You can do something like

import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor() {
    super();
    this.state = {
    lists: ["Dogs", "Cats"],
    items: {Dogs:[], Cats:[]}
    };
  }

  handleAddItem(item) {
    console.log(this.props.idName);
    console.log(item);
    let oldItems = this.state.items;
    oldItems[this.props.idName].push(item);
    // Update new state for items
    this.setState({
      items: {...this.state.items}
    })

  }

How To Create, Modify, and Loop through Objects in JavaScript , JavaScript arrays are also a type of object. A method is a function that is the value of an object property, and therefore a task that an object  But then if you need to update it in response to a property changing, you need to use the watcher. NOTE: Be careful with using a watch to update state. This means that both your component and the parent component are updating — directly or indirectly — the same state. This can get very ugly very fast. Watching nested data — Arrays and Objects

Immutability in Array of objects, using Map method, modify the object's properties with help of the spread operator {} . In line 22, you can see that we are overwriting the original object with a newly created one and  We can also use Array's map function to modify object of an array using Javascript. function changeDesc(value, desc){ projects.map((project) => project.value == value ? project.desc = desc : null) } changeDesc('jquery', 'new description')

Updating a value in a nested array of objects, We first want to find the index in the array of the object, or where the object is located in the array. You can find the element by any key, id or name, or any other  Updating properties of an object in React state. I would like to have a generic method to update the object. even it’s nested in objects or arrays.

Reactivity / Updating arrays and objects • Svelte Tutorial, Assignments to properties of arrays and objects — e.g. obj.foo += 1 or array[i] = x — work the same way as assignments to the values themselves. function  Using ES6 syntax's spread operator to shallow copy an array, creating or updating a property of an object at a given index of the array would look like this: this.setState(prevState => { const newItems = [prevState.items]; newItems[index].name = newName; return {items: newItems}; })

Comments
  • Not answering your question, but try to keep your flat is a good practice. stackoverflow.com/questions/38842454/…
  • @konekoya thank you
  • It is better to use setState with callback function in such case: reactjs.org/docs/react-component.html#setstate
  • From React docs - this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
  • yeah. for things like incrementing etc I see the point, how would your solution look like? I don't see a more "atomic" way to do it.
  • I get this error App.js:5 Uncaught TypeError: Cannot convert undefined or null to object
  • @amaj Thanks for pointing this out! Good watch! I updated the code accordingly. You example is not using the props from the updater function, so you may fix your code as well :)
  • Am updating the previous state variable to be make it ready to update for the next state. You can see spread operator in the this.setState call which updates it how react wants. Let me update the answer to make it clear.
  • You can pass function in setState, where you have access to oldState and you don't have to save previous state value, check docs: reactjs.org/docs/react-component.html#setstate
  • This may corrupt data! The setState call would overwrite the other category!
  • @lipp. How so ?
  • @agent_hunt this.state.items gets replaced entirely. If this.state.items.Cats = [{name: 'foo'}] and idName = 'Dogs', the 'Cats' get removed. That said: I just noticed, that your are missing "one level". It is e.g. this.state.items.Cats = [{name: 'foo'}] ... and not this.state.items = [{name: 'foo'}]