1

I want to dynamically generate a 50 element array from a single element, by just modifying one value on each loop.

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 end up with 50 copies of same element with s3.object.key = F7kdfh2Dj3j2s8/uploads/10000_users_without_password-20190102T030405Z/49.csv.

2
  • Object.assign is not a deep copy, for copying nested object one method is JSON.parse(JSON.stringify(obj)) Commented Aug 28, 2019 at 13:24
  • 1
    Take a look into deep cloning. In your example, the s3 and/or object is being passed by reference and therefore assigning the key to one, affects all records. Commented Aug 28, 2019 at 13:25

1 Answer 1

4

it's because you're creating a shallow copy of Records[0], use 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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.