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

Searching array like below but it returns null

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

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

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