0

I want to set object with data and then pushed it to another object

let globalSamples = {} as any;
let sample = { } as ISamplesDetail [];
sample = [];
for (let i = 0 ; i<this.prelevementLingette.samplesDetail.length; i++)
    {
      sample [i].id= this.old.samplesDetail[i].id;
      sample [i].reference=this.old.samplesDetail[i].reference;
}
globalSamples.push(sample);

I got this error 'Cannot set property 'reference' of undefined'

How can I resolve the problem ?

1
  • use an if statement. something like if (!sample[i]) continue; in order to jump to the next iteration if sample[i] is null or undefined. Commented Dec 19, 2017 at 14:52

1 Answer 1

1

There are a few problems in your code, so I've cleaned it up a bit

// looks like this would be a proper type..
const globalSamples: ISamplesDetail[][] = [];

// can't assign object ({}) what should be an array, so..
// value doesn't change -> const
const sample: ISamplesDetail[] = [];


// it's strange that you iterate over 'this.prelevementLingette',
// but access 'this.old'
for (let i = 0 ; i < this.prelevementLingette.samplesDetail.length; i++) {
      sample[i] = {
          id: this.old.samplesDetail[i].id,
          reference: this.old.samplesDetail[i].reference
      }
}

// can't push to an object (should be array - [])
globalSamples.push(sample);

It seems like the logic in your code is a bit twisted, but it's difficult to say without knowing the context

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

2 Comments

It works! What do we call this syntax ? And Why my code doesn't work. It's seems the same
what syntax exactly?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.