最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to iterate over a dictionary of arrays (without knowing the key name) - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Apr 12, 2019 at 21:08 Jack Bashford 44.1k11 gold badges55 silver badges82 bronze badges asked Apr 12, 2019 at 20:59 m.a.d.catm.a.d.cat 2073 silver badges10 bronze badges 3
  • 4 zk[i][j] is the array ? But you should actually change your datastructure, either use an array of objects or one object with keys for lookup, not both. – Jonas Wilms Commented Apr 12, 2019 at 21:01
  • You can use for..of to iterate through values instead of keys developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – nucleartux Commented Apr 12, 2019 at 21:02
  • 1 thing.map(Object.values) or thing.flatMap(Object.values) or thing.flatMap(Object.values).flat() depending on how exactly you want it. – georg Commented Apr 12, 2019 at 21:16
Add a ment  | 

7 Answers 7

Reset to default 4

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

You missed the object of which value has to be printed

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

The issue is that you're missing one level of your loop. You have to loop over the outer array, then loop over the keys in each object, then if that key's value is an array loop over that array.

If for example you want to log all the values then you can use Object.prototype.keys() it returns an array of the keys in an object so you can try something like this:

const arr = [
        {"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"]}
    ];

    arr.forEach(x => {
      Object.keys(x).forEach(k => {
        if (Array.isArray(x[k])) {
          x[k].forEach(v => {
            console.log(v);
          });
        } else {
          console.log(x[k]);
        }
      });
    });

You could take a differetn approach for iterating the given arrays and objects, with

  • Array#forEach for iterating an array,

  • Object.entries for getting an array of arrays with keys and values and a

  • destructuring assignment for an array of key/value pairs.

var data = [{ 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"] }];

data.forEach((object, outerIndex) =>
    Object.entries(object).forEach(([key, array]) => 
        array.forEach((value, innerIndex) => 
            console.log(outerIndex, key, innerIndex, value)
        )
    )
);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Use Object.values:

const arr = [
    {"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"]}
];

arr.forEach(obj => console.log(Object.values(obj)));
.as-console-wrapper { max-height: 100% !important; top: auto; }

Object.entries would be helpful if you are trying to iterate over and output each object key and each of the values in the corresponding array. There are more pact ways to do this, but the nested loops should clearly illustrate what is happening.

const arr = [
  {"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"]}
];

for (const obj of arr) {
  for (const [key, values] of Object.entries(obj)) {
    console.log(`KEY: ${key}`);
    console.log('VALUES: ');
    for (const value of values) {
      console.log(value);
    }
  }
}
// Example output from first object...
// KEY: key1
// VALUES: 
// 2019-04-12-14:54:29.190
// 19
// 0
// 4325
// 1

In js you always get the keys so what you do is:

for (var i in zk) {
    for (var j in zk[i]) { // j will be key1, key2 etc
        console.log(zk[i][j]); // arrays  ["2019-04-12-14:54:29.190", "19", "0", "4325", "1"] over where you can iterate
        for (var k in zk[i][j]) {
            console.log(zk[i][j][k]); // "2019-04-12-14:54:29.190" etc
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论