gpt4 book ai didi

javascript - 为什么对象值被插入数组 3 次?

转载 作者:行者123 更新时间:2023-12-02 16:04:01 25 4
gpt4 key购买 nike

我有一个简单的对象数组,我将一个包含 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);
});
},

最佳答案

您在每次迭代中将相同的对象插入数组:

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

关于javascript - 为什么对象值被插入数组 3 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30932473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com