-1

I have a state "Bill" and I want to delete one of item in "Product" with "ProductID". So how can I do it?

Bill = {
  "Bill_ID" : "a00231",
  "Products" : [
    {
      "ProductID" : "P0203",
      "ProductName" : "ABCD"
    },
    {
      "ProductID" : "P023243",
      "ProductName" : "ZYZ"
    }
  ]
}

How can I update the state after delete product item?

Chris
  • 57,622
  • 19
  • 111
  • 137
  • 1
    Please post the code, asking for a solution without initial struggle doesn't help. – buoyantair Oct 13 '17 at 14:10
  • Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – bennygenel Oct 13 '17 at 14:31

2 Answers2

0

I think you could use thepop() method. You can pop the last element from your products array and look at the popped element. Something like:

var poppedElement = Bill.Products.pop();
console.log(Bill)              //Bill withoug last Products element
console.log(poppedElement)     //just the last element of Products

Not sure if this will work completely off the top of my head, but hopefully will give you a starting place at least :)

Check out this link for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

Let me know how it goes!

CodeMonkey123
  • 1,046
  • 13
  • 22
0

You can use filter on bill.products array, like following (note it must be != not ==)

bill.products.filter(x => x != yourDesiredToBeDeletedId)

Treat this.state as if it were immutable

Since your state contains an array within an object, I suggest to use lodash's cloneDeep.

let newBill = _.cloneDeep(this.bill);
newBill.products = newBill.products.filter(x => x != yourDesiredToBeDeletedId);
this.setState(bill: newBill);
An Nguyen
  • 1,487
  • 10
  • 21