Search code examples
javascriptarraysobject

How to iterate over a dictionary of arrays (without knowing the key name)


I have a an object that looks similar to this:

[
    {"key1": ["2019-04-12-14:54:29.190", "19", "0", "4325", "1"]},
    {"key2": ["2019-04-12-14:54:29.191", "20", "0", "2212", "1"]},
    {"key3": ["2019-04-12-14:54:29.192", "22", "0", "4376", "0"]}
]

However I do NOT know the names of the keys (ie key1, key2 and key3 names are not known to me).

This post is almost exactly what I want, except that method requires you to know the names of the keys.

I need to be able to iterate over the key name and it's value array.

I've tried this:

for (var i in zk) {
    for (var j in zk[i]) {
        console.log(j)
    }
}

But that only prints the key names. How can I iterate through the list as well? In most langues iterating over j seems the logical choice but not in this case. Any ideas? Thank you.


Solution

  • Let's continue from the code sample you have provided.

    1) Getting the keys of each element

    for (let i in zk) {
      for (let j in zk[i]) {
        console.log(j)
      }
    }
    

    2) Getting the list within each element

    for (let i in zk) {
      for (let j in zk[i]) {
        console.log(zk[i][j])
      }
    }
    

    3) Iterating through each list within each element

    for (let i in zk) {
      for (let j in zk[i]) {
        for (let k = 0; k < zk[i][j].length; k++) {
          console.log(zk[i][j][k])
        }
      }
    }
    

    Alternatively, you can use Object.values, which returns the values of each key-value pair. You can consider using Array.map() too.

    for (let i in zk) {
      Object.values(zk[i]).map(list => {
        list.map(element => {
          console.log(element);
        });
      });
    }