1

I am building out a shopping cart component and have a function to add new items. My object structure looks like so:

 productsArray = [{
    "item": {
     "id": 001,
     "name": "dinner plate",
     "description": "white corningware plate",
     "collection": "dinner",
     "price": 50,
    },
     "qty": 1,
   }]

if my addProduct function is called on a different item, it pushes a new object to the array. However I want to ensure that if some code runs in the application such as delete, pop or an attempt to change a property's value - it will not change the object. I still, however, would like to be able to change the qty value if the addProduct function executes and there is a matching object (which will execute qty += 1).

I understand there are Object.freeze and Object.seal at my disposal but I am running into errors in allowing only the one property to be modified. Any help would be greatly appreciated.

kilnerbank
  • 19
  • 4
  • Please [search](/search?q=%5Bjs%5D+create+a+read+only+property) before posting. More about searching [here](/help/searching). You can make a single property read-only by using [`Object.defineProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) with `writable: false` (or just leave `writable` off, all the flags default to `false`). If you want to make it *really* hard, make `configurable` `false` as well. – T.J. Crowder Oct 16 '22 at 10:57
  • Doing that is great for avoiding accidentally updating the property, but it won't stop someone who's actively determined to bypass your protections. It'll make it that you can't change `qty` directly in the object, but it's easy enough to *replace* the object in the array: `productsArray[0] = {...productsArray[0], qty: 1000};`. So you'll need to do more than just make the property read-only if you need paranoia-level protection. – T.J. Crowder Oct 16 '22 at 10:59

0 Answers0