简体   繁体   中英

How to update object property which is an array?

I am working in a ReactJS project and have a filterGroupsData property in my state. This is an array of objects, each object has a filters property which is an array of string values. See below:

filterGroupsData:[
    {"key":1532957059388,"id":1532957059388,"filters":[]},        
    {"key":1532957059612,"id":1532957059612,"filters":[]},        
    {"key":1532957059847,"id":1532957059847,"filters":[]}
]

How can I add elements to the filters property of a object with a given id?

I attempted to this but this results in overwriting the whole object with on value:

// update the filter array of the object with id == activeId
let updatedFilterGroupsData = filterGroupsData.map(filterGroupData => filterGroupData.id === activeId ? filterGroupData.filters.push('test') : filterGroupData)

this.setState({filterGroupsData: updatedFilterGroupsData});

Appreciate any help.

Here: filterGroupData.filters = 'test'

You're setting the prop value to a string instead of putting in the array.

You need to push the item into the filters array like:

filterGroupData.filters.push('test');

filters is a array so you need to use push('test') with multi line code inside map :

 var filterGroupsData = [ {"key":1532957059388,"id":1532957059388,"filters":[]}, {"key":1532957059612,"id":1532957059612,"filters":[]}, {"key":1532957059847,"id":1532957059847,"filters":[]} ] var activeId = 1532957059612; let updatedFilterGroupsData = filterGroupsData.map((filterGroupData) => { if(filterGroupData.id === activeId) { filterGroupData.filters.push('test'); } return filterGroupData }); console.log(updatedFilterGroupsData); 

You can use findIndex to get the index of the filter group you want to update, and then create a copy of the object and the filters array and add a new entry to it.

Example

const id = 1532957059388;

this.setState(previousState => {
  const filterGroupsData = [...previousState.filterGroupsData];
  const index = filterGroupsData.findIndex(group => group.id === id);

  filterGroupsData[index] = {
    ...filterGroupsData[index],
    filters: [...filterGroupsData[index].filters, "new filter"]
  };

  return { filterGroupsData };
});

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