Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading