Access a property within the same object without declaring it in Javascript

I have an array of objects that I need to loop through to create a new object with different properties. The problem is that when creating the new object I need to access a property before it is declared.

This is my source object:

let data = [
  {
    "name": "one",
    "total": 12,
    "fec": "001"
  },
  {
    "name": "one",
    "total": 1,
    "fec": "002"
  },
  {
    "name": "two",
    "total": 5,
    "fec": "001"
  }  
]

This is what I do:

let result;
data.forEach((item) => {
  result = {
    name: item.name,
    result: data.find((item) => item.fec === '001') ?.total,
    dto: this.result + 5
  }
})

My problem: how can I access the result property from the dto property inside the forEach()

>Solution :

Put the value in a variable before putting it in the result object.

let result;
data.forEach((item) => {
  let r = data.find((item) => item.fec === '001')?.total;
  result = {
    name: item.name,
    result: r,
    dto: r + 5
  }
})

Leave a Reply