0

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()

element
  • 49
  • 5
  • 1
    What's the point of the `forEach` loop? At the end, `result` will just contain the object from the last element of `data`. – Barmar Apr 04 '23 at 16:05
  • 1
    The language does not allow references to "under-construction" objects in the middle of the object initializer. – Pointy Apr 04 '23 at 16:06
  • you can save the `data.find((item) => item.fec === '001') ?.total` to a variable and access it inside the object – cmgchess Apr 04 '23 at 16:08

1 Answers1

4

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

Your code also isn't returning all the results, it keeps overwriting the result variable with a different object. Use map() to return all of them as an array.

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

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

console.log(result);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What does that ```?.total```, questionmark and dot means here? – Nexo Apr 04 '23 at 16:16
  • [optional chaining](https://stackoverflow.com/questions/61847231/question-mark-before-dot-in-javscript-react) – Barmar Apr 04 '23 at 16:17
  • @Barmar Sorry but when I list elements in data, I cannot see a difference before and after your code. So what is result and how to access it? Did you add a property in data or elsewhere??? Comments more than appreciated! Thank you! – tatactic Apr 04 '23 at 18:10
  • It's not changing the original `data`, it's creating a new object and assigning that to `result`. – Barmar Apr 04 '23 at 18:11
  • @Barmar I only get a function when I try to access it and don't find any key nor index – tatactic Apr 04 '23 at 18:13
  • I've updated the answer to show how to get all the results. – Barmar Apr 04 '23 at 18:13