简体   繁体   中英

Javascript update specific element in object array based on subset

I understand that you should use setstate to update state in React. I have an array of objects in state and I would like to update a specific element. How can I do that. My data and code is the following:

var trans = [{
    "_id" : ObjectId("583f6e6d14c8042dd7c979e6"),
    "transid" : 1,
    "acct" : "acct1",
    "transdate" : ISODate("2012-01-31T05:00:00.000Z"),
    "category" : "category1",
    "amount" : 103
},
{
    "_id" : ObjectId("583f6e6d14c8042dd7c2132t6"),
    "transid" : 2,
    "acct" : "acct2",
    "transdate" : ISODate("2012-01-31T05:00:00.000Z"),
    "category" : "category2",
    "amount" : 103
},
{
    "_id" : ObjectId("583f6e6d14c8042dd7c152g2"),
    "transid" : 3,
    "acct" : "acct3",
    "transdate" : ISODate("2012-01-31T05:00:00.000Z"),
    "category" : "category3",
    "amount" : 103
}]

  let transFilter=[];

    trans.forEach(function(el){
        if(parseInt(el.transid).indexOf(parseInt(1))!=-1)
        transFilter.push(el);
    });

    transFilter.category = "category4";

//this is where I'm not sure how to just update the corresponding record to
//the one in transFilter for tmpTrans; the data in trans is a copy of the data in tmpTrans
           this.setState({tmpTrans: transFilter}, function () {
           console.log(tmpTrans);
            });

map is aa fairly straightforward function you can use to create a modified array.

Consider the following array of items:

var data = [
  { id: 1, category: 'sports' }, 
  { id: 2, category: 'movies' }
]

If you want to change the category of item with id of 2 you can map over your array and use Object.assign to create a copy of your object with the new category, if the id matches:

var newData = data.map(item => {
  if (item.id === 2) {
    return Object.assign({}, item, { category: 'food' })
  }
  return item
})

Now with your newly minted data you can simply set the state:

this.setState({ data: newData })

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