How to update and assign an array of object to a new variable

I have an array of object which looks like ->

const test - [{id: '1', marks: '32'},{id: '2', marks: '31'},{id: '3', marks: '12'}]

Now, here I am trying to update this array of object so that I want to add one more key value in each object.

setPrevious = test => {
    const {
      nav: {
        queryParams: { bspId }
      }
    } = stores
    const copyTest = _.cloneDeep(test)
     this.productCommentsAdded =  copyTest?.forEach(marks => {
      marks.productId = bspId
    })
  }
  
  setPrevious(test)

with this, sets the this.productCommentsAdded to undefined . So, what is the proper way to do this ? update it and assign to that variable

21 thoughts on “How to update and assign an array of object to a new variable”

  1. forEach does not return anything, so that would cause productsCommentsAdded to always end up as undefined. (If copyTest is undefined, that would also cause this, so that may be another issue to look into.) But assuming that copyTest is defined, one approach is to use map here to achieve what you want, like this:

        this.productCommentsAdded = copyTest?.map(marks => {
          return {...marks, productId: bspId};
        })
    

    This creates a new array, containing a copy of each object in copyTest, (using the object spread operator, which is what the ... part is called), and adds a new property productId to each of those new objects. The original copyTest array objects are unchanged; the new array with the new properties is returned by map and assigned to this.productCommentsAdded.
    More info on map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    If you don’t care whether or not the original copyTest array’s objects are modified, you can also do this with forEach as follows:

        copyTest?.forEach(marks => {
          marks.productId = bspId;
        })
        this.productCommentsAdded = copyTest;
    

    but the first way with map is generally a better practice (less likely to be surprising bugs due to mutating the original array’s elements.)

    Reply

Leave a Comment