skip to Main Content

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


  1. 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:

    <script type="module">
    
    import JSON5 from 'https://unpkg.com/json5@2/dist/index.min.mjs'
    
    const array = ["[{'city': 'new york', 'state': 'ny'}]", "[{'city': 'dallas', 'state': 'tx'}]", "","[{'city': 'los angeles', 'state': 'ca'}]"];
    const result = array.map(s => s ? JSON5.parse(s) : null);
    console.log(result);
    
    </script>
    Login or Signup to reply.
  2. 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)
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search