Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object key using async.each

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

like image 516
Jon Hunter Avatar asked Jul 02 '15 08:07

Jon Hunter


1 Answers

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);
  }
});
like image 133
Alberto Zaccagni Avatar answered Nov 03 '22 01:11

Alberto Zaccagni