I have some data which is an array of arrays, each sub-array is length one and the only item in that array is an object with key value pairs. As an example:
const array = [[{'city': 'new york', 'state': 'ny'}], [{'city': 'dallas', 'state': 'tx'}], ,[{'city': 'los angeles', 'state': 'ca'}]]
I am trying to loop through this array and pull out only the cities. I can do that by running
array.forEach(item => console.log(item[0].city))
However, when I try this on my actual data (which I unfortunately cannot share) I get the error
TypeError: Cannot read properties of undefined (reading 'city')
When I try to run just
array.forEach(item => console.log(item[0]))
the only thing that gets returned is a bunch of [, plus one undefined for the blank entry.
If it is relevant, the actual data that I am trying to index into is a column pulled from a Google Sheet.
Does anyone know why I am unable to properly iterate through my data and any possible solutions around it?
As Parvez pointed out, my array is being pulled from the data as an array of strings, rather than an array of arrays. That means that my data actually looks like
const array = ["[{'city': 'new york', 'state': 'ny'}]", "[{'city': 'dallas', 'state': 'tx'}]", "","[{'city': 'los angeles', 'state': 'ca'}]"]
If anyone has any suggestions for how to work with those sub-arrays so that I can pull out the relevant data, I would greatly appreciate it.
>Solution :
Please try like this.
const array = [[{'city': 'new york', 'state': 'ny'}], [{'city': 'dallas', 'state': 'tx'}], ,[{'city': 'los angeles', 'state': 'ca'}]]
array.map((element)=> {
const [{city, state}] = element;
console.log(city)
})