我想通过仅在每个循环上修改一个值来从单个元素动态生成50个元素的数组。

const eventRecords = { Records: [] }
      for (let i = 0; i < 50; i++) {
        const aRecord = Object.assign({}, eventS3Chunk.Records[0])
        aRecord.s3.object.key = `F7kdfh2Dj3j2s8/uploads/10000_users_without_password-20190102T030405Z/${i}.csv`
        eventRecords.Records.push(Object.assign({}, aRecord))
      }


eventRecords.Records最终以s3.object.key = F7kdfh2Dj3j2s8/uploads/10000_users_without_password-20190102T030405Z/49.csv包含50个相同元素的副本。

最佳答案

这是因为您要创建Records[0]的浅表副本,请使用JSON.parse(JSON.stringify(eventS3Chunk.Records[0]));
 :


const eventS3Chunk = {
  Records: [{
    s3: {
      object: {
        key: "a"
      }
    }
  }]
};

const eventRecords = Array.from({
  length: 50
}, (_, i) => {
  const aRecord = JSON.parse(JSON.stringify(eventS3Chunk.Records[0]));
  aRecord.s3.object.key = `F7kdfh2Dj3j2s8/uploads/10000_users_without_password-20190102T030405Z/${i}.csv`;
  return aRecord;
});

console.log(eventRecords)

关于javascript - 将元素插入数组以进行循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57693438/

10-12 05:34