-2

Here is my object in a map function:

element: {2021-12-03: Array(12)}

How to I access the Array?

I've tried this:

element.date

But I get 'undefined'

Page COW
  • 515
  • 13
  • 31
  • 4
    The parameter in your object isn't named 'date', it's named '2021-12-03'. Try element['2021-12-03'] – Brendan Bond Dec 03 '21 at 17:00
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Ivar Dec 03 '21 at 17:00

3 Answers3

1

To access properties of an object where the property name contains problematic characters like e.g. ., (), #, -, +, * , / or (space), use the square bracket [] notation and pass in the name of the property as a string:

element['2021-12-03'] // returns your array
connexo
  • 53,704
  • 14
  • 91
  • 128
0

I'd recommend restructuring your element such that:

element: {
   date: '2021-12-03',
   items: [....] // Array(12)....
}

then if you had something like an array of element you could find a specific date via:

my_element = elements.find(x => x.date === '2021-12-03')
iamaword
  • 1,327
  • 8
  • 17
0

You can restructure as @iamaword said. like this:

let data = {'2021-12-03': [1,2,3,4], '2021-11-03': [5,6,7,8]}

let elements = Object.entries(data).map(item => {
  return {date: item[0], items: item[1]} // Depends on you.
});

elements.forEach(element => {
 console.log(`${element.date}:${JSON.stringify(element.items)}`);
});
Batuhan
  • 1,521
  • 12
  • 29