7

I have some JSON data as follows:

{ 
    version: 1,
    partitions: { 
        '0': [ 1616133379 ], 
        '1': [ 1616133378 ], 
        '2': [ 1616133380 ] 
    } 
}

I am looping through the data using async.each as follows:

async.each(topicData.partitions, function(data, callback){
    console.log('/brokers/topics/' + topic + '/partitions/' + data + '/state');
    callback();
},
function(err){
    if(err) {
        console.log(err);
        callback(err);
    }
});

The output I'm getting is:

'/brokers/topics/testing/partitions/1616133379/state' '/brokers/topics/testing/partitions/1616133378/state' '/brokers/topics/testing/partitions/1616133380/state'

As you can see the data item passed through the async.each function is holding the value of the key/value pair whereas I actually want it to pass the key to produce this output:

'/brokers/topics/testing/partitions/0/state' '/brokers/topics/testing/partitions/1/state' '/brokers/topics/testing/partitions/2/state'

Is there anyway I can get the key passed as opposed to the value?

This has to be run asynchronously.

Thanks

TaoPR
  • 5,932
  • 3
  • 25
  • 35
Jon Hunter
  • 882
  • 2
  • 8
  • 18

2 Answers2

9

You could use forEachOf, the iterator gets passed the value and key of each item in case of an object.

iterator(item, key, callback) - A function to apply to each item in obj. The key is the item's key, or index in the case of an array. The iterator is passed a callback(err) which must be called once it has completed. If no error has occurred, the callback should be run without arguments or with an explicit null argument.

Usage:

async.forEachOf(topicData.partitions, function(item, key, callback){
  console.log('/brokers/topics/' + topic + '/partitions/' + key + '/state');
  callback();
}, function(err){
  if(err) {
    console.log(err);
    callback(err);
  }
});
Jon Hunter
  • 882
  • 2
  • 8
  • 18
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
0

Try to put this in your loop.

console.log(topicData.partitions.indexOf(data));
Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56
  • That just threw an error `console.log(topicData.partitions.indexOf(data)); ^ TypeError: Object # has no method 'indexOf'` – Jon Hunter Jul 02 '15 at 08:59