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.
2
Answers
The strings in your data have JavaScript notation and not JSON, which is a pity. If you control the source of the data it would be a good idea to make sure it has JSON compatible strings.
If not, then
eval
could help, but it has the major downside that it opens up the risk of code injection.The compromise could be to use a parser that also accept single quote delimiters. There happens to be a popular library JSON5 that does that.
Here is a demo for your sample. Note that an empty string will not be considered valid input (as it is not JSON), so you need to deal with those yourself. Here I will translate those to
null
:Please try like this.