[英]Get object key using async.each
I have some JSON data as follows: 我有一些JSON数据如下:
{
version: 1,
partitions: {
'0': [ 1616133379 ],
'1': [ 1616133378 ],
'2': [ 1616133380 ]
}
}
I am looping through the data using async.each as follows: 我使用async.each循环遍历数据,如下所示:
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'
'/ 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: 正如您所看到的,通过
async.each
函数传递的data
项保持键/值对的值,而我实际上希望它传递键以产生此输出:
'/brokers/topics/testing/partitions/0/state' '/brokers/topics/testing/partitions/1/state' '/brokers/topics/testing/partitions/2/state'
'/ brokers / topics / testing / partitions / 0 / state''/ brokers / topics / testing / partitions / 1 / state''/ broker / 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 谢谢
You could use forEachOf
, the iterator gets passed the value and key of each item in case of an object. 您可以使用
forEachOf
,迭代器会在对象的情况下传递每个项的值和键。
iterator(item, key, callback) - A function to apply to each item in obj.
iterator(item,key,callback) - 一个应用于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.
迭代器传递一个回调(err),一旦完成就必须调用它。 If no error has occurred, the callback should be run without arguments or with an explicit null argument.
如果没有发生错误,则应该在没有参数或显式null参数的情况下运行回调。
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);
}
});
试着把它放在你的循环中。
console.log(topicData.partitions.indexOf(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.