1

I want to duplicate one array of objects into multiple ones, because every one of them I need to use in separate places.

if(!this.tempLookups){
    for (let count = 0; count < this.dates.length; count++) {
       this.tempLookups[count] = this.lookups[key];
    }
}

Error: Uncaught (in promise) TypeError: Cannot set property '0' of null

5
  • 1
    this.tempLookups = [] after the if condition Commented Jan 8, 2020 at 8:32
  • 1
    Awkward, Pranav,you right! Thank you! Commented Jan 8, 2020 at 8:34
  • You can do it in single line without a for loop, like this.tempLookups = new Array(this.dates.length).fill(this.lookups[key]) Commented Jan 8, 2020 at 8:39
  • is this.lookups[key] an array? Commented Jan 8, 2020 at 8:59
  • If this.lookups is array of arrays, than you should use Array.from to create shallow copy of this.lookups[key] array - see my answer. Commented Jan 8, 2020 at 10:46

2 Answers 2

1

The actual reason for the error is clearly in error message that you are trying to set the property for a null. So in order to fix simply define it after the if.

if(!this.tempLookups){
    his.tempLookups = [];
    for (let count = 0; count < this.dates.length; count++) {
       this.tempLookups[count] = this.lookups[key];
    }
}

You can do it in a single line without a for loop using Array#fill method since you are filling with the same value.

if(!this.tempLookups){    
   this.tempLookups = new Array(this.dates.length).fill(this.lookups[key]);
} 
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this like this:

if (!this.tempLookups) {
    this.tempLookups = [];
    for (let i = 0; i < this.dates.length; i++) {
       this.tempLookups.push(Array.from(this.lookups[key]));
    }
}

Note that the this.tempLookups variable is initialized as empty array before we start inserting data. The Array.from call in for loop makes sure we actually create (shallow) copies of the this.lookups[key] array, instead of just assigning reference to the same this.lookups[key] array multiple times. Without Array.from changing one array would change all of them - because in reality there would be only one array referenced multiple times.

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.