我有一个简单的对象数组,我在其中推送一个包含2个字段的对象:bucketName和Date。问题是这些值被三次推入数组。请帮我。
JS:
sortBucket: function(bucketList) {
var counter, j = 0;
var str = "aws-billing-csv";
console.log("Bucket List :: ", bucketList);
bucketList.forEach(function(bucket, index) {
(function(bucketId) {
var bucketObj = {};
// console.log("Bucket Id :: ",bucketId);
s3Client.listObjects(params = {Bucket: bucketId }, function(err, data) {
var csvBucketArr = [];
if (err) {
document.getElementById('status').innerHTML = 'Could not load objects from ' + bucketID;
}
else{
//console.log("Bucket Data "+index+" :: ",data);
data.Contents.forEach(function(content,contentIndex){
var fileKey = content.Key;
if(fileKey.search(str) != -1) {
// console.log("fileKey["+bucketId+"] "+contentIndex+" :: ",fileKey + " Date :: " ,content.LastModified);
bucketObj[fileKey] = {
lastModified : content.LastModified,
bucketName : bucketId
}
if(!jQuery.isEmptyObject(bucketObj)){
csvBucketArr.push(bucketObj);
}
}
});
csv = csvBucketArr;
}
if(csvBucketArr.length!==0)
console.log("csvBucketArr :: ",csvBucketArr));
});
}(bucket.bucketName));
// console.log("Bucket " + index + " :: ", bucket);
});
},
答案 0 :(得分:2)
您在每次迭代中将同一个对象推送到数组中:
data.Contents.forEach(function(content,contentIndex){...});
因此,与.forEach()
循环迭代的次数一样,您最终会将完全相同的bucketObj
对象推送到csvBucketArr
数组中。
如果你希望.forEach()
的每次迭代都将一个新的,不同的bucketObj
对象放入数组中,那么你需要每次在该循环中创建一个新对象,如下所示:
sortBucket: function(bucketList) {
var counter, j = 0;
var str = "aws-billing-csv";
console.log("Bucket List :: ", bucketList);
bucketList.forEach(function(bucket, index) {
(function(bucketId) {
// console.log("Bucket Id :: ",bucketId);
s3Client.listObjects(params = {Bucket: bucketId }, function(err, data) {
var csvBucketArr = [];
if (err) {
document.getElementById('status').innerHTML = 'Could not load objects from ' + bucketID;
}
else{
//console.log("Bucket Data "+index+" :: ",data);
data.Contents.forEach(function(content,contentIndex){
// ===> create new bucketObj object
var bucketObj = {};
var fileKey = content.Key;
if(fileKey.search(str) != -1) {
// console.log("fileKey["+bucketId+"] "+contentIndex+" :: ",fileKey + " Date :: " ,content.LastModified);
bucketObj[fileKey] = {
lastModified : content.LastModified,
bucketName : bucketId
}
if(!jQuery.isEmptyObject(bucketObj)){
csvBucketArr.push(bucketObj);
}
}
});
csv = csvBucketArr;
}
if(csvBucketArr.length!==0)
console.log("csvBucketArr :: ",csvBucketArr));
});
}(bucket.bucketName));
// console.log("Bucket " + index + " :: ", bucket);
});
},