Why Am I not getting add a new key and value to an existence object?

I Have the follow object which iterating it I can add a new key and value, but when I have to make a database search and take each result and add as a new key + value does not work, the Eslint point a Assignment to property of function parameter 'object'.eslintno-param-reassign, bellow is the example without make a database search.

const obj = {
  Cod: 43453,
  Informations: [
    {
      codPay: 802112,
      value: 80
    },
    {
      codPay: 802113,
      value: 80
    },
    {
      codPay: 802114,
      value: 80
    },
    {
      codPay: 802115,
      value: 80
    },
    {
      codPay: 802116,
      value: 80
    },
    {
      codPay: 802117,
      value: 80
    },
    {
      codPay: 802118,
      value: 80
    },
    {
      codPay: 802119,
      value: 80
    }
  ],
  status: 'OK'
}



obj["Informations"].forEach((f,index) => {
    f.more_info = index
})

console.log(obj)

By making database search:

obj["Informations"].forEach(asyn(f) => {
    const result = db.any("Select info From table where cod $1",f.codPay")
    f.more_info = result[0].info
})

by openning this db.any the values is coming correct but I cannot add new key, where Am I missing?

1 thought on “Why Am I not getting add a new key and value to an existence object?”

  1. The no-param-reassign rule is there to warn you that mutating the argument may cause undesirable effects elsewhere in the code. For example, there may be some other part of the code that relies on the assumption that each Informations sub-object contains only codPay and value properties, and nothing else (no more_info property). If such code existed, your addition of a more_info property could cause that code to stop working.

    A good alternative is to use .map, to create entirely new objects instead of mutating the original ones. That will fix the linter warning.

    Another issue is that it looks like db.any returns a Promise, in which case you should wait for it to resolve first. To do this in a loop, use Promise.all to wait for all Promises in an array to resolve.

    const informationsWithMoreInfo = await Promise.all(
        obj.Informations.map(
            obj => db.any("Select info From table where cod $1", obj.codPay)
                .then(result => ({ ...obj, more_info: result[0].info }))
        )
    );
    // do stuff with informationsWithMoreInfo
    

    For the await to work, make sure the containing function is async – either that, or call .then on the Promise.

    Reply

Leave a Comment