0

I have following data

indexMap = {"A": 0, "B": 1};
self.ctx.chart.data.datasets = [
    {
        "label" : "A",
        "data" : [0,0,0,0,0]
    },
    {
        "label" : "B",
        "data" : [0,0,0,0,0]
    },
]

When I want to access data array of the first object of the datasets array,
I write the code below :

var idx = indexMap["A"];
var data = self.ctx.chart.data.datasets[idx].data; // <--- error occur [TypeError: Cannot read property 'data' of undefined]

But the error occurs, that says:

TypeError: Cannot read property 'data' of undefined

But the self.ctx.chart.data.datasets[idx] can print the value like below:

{
    "label" : "A",
    "data" : [0,0,0,0,0]
}

the variable self.ctx.chart.data.datasets[idx] really has the key 'data'

How do I fix it?
BTW, when I using the code below is no problem, why?

var idx = 0;
var data = self.ctx.chart.data.datasets[idx].data; // <--- this is ok!!! why!!!!
6
  • See weather you are getting 0 for indexMap["A"] Commented Jul 31, 2020 at 5:23
  • 2
    As said by @YerrapotuManojKiran, I'd log the value of indexMap["A"] in the scope you are accessing it in. This error makes me suspect that indexMap is not in scope. Commented Jul 31, 2020 at 5:27
  • Are either of the objects populated asynchronously? Commented Jul 31, 2020 at 5:32
  • Using a “map” to resolve a value makes no difference to the value used later, assuming it is the same value. Hence, given the code, it must be a different value. (And likely hypotheses are the “map” usage is incorrect or the problem is misrepresented.) Commented Jul 31, 2020 at 5:43
  • @adiga if objects populated asynchronously, the error will occur ? sorry i'm not good at this, thx Commented Jul 31, 2020 at 5:59

1 Answer 1

1

It is working fine if the data provided are correct

 let indexMap = {"A": 0, "B": 1};
    
    this.ctx = [
        {
            "label" : "A",
            "data" : [0,0,0,0,0]
        },
        {
            "label" : "B",
            "data" : [0,0,0,0,0]
        },
    ];
    
    let id = indexMap["A"];
    console.log((id))
    
     this.result = this.ctx[id].data; 

CheckThis

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

2 Comments

If it works as it is, please flag it as not reproducible instead of answering.(The question was closed but reopened for some reason). The question has no future value to the site. If the question has upvoted answers, OP or roomba can't delete it and it sticks around forever.
@adiga I have assigned the input to one variable rather he mentioned like self.ctx.chart.data.datasets. Then after only its works. So it may related to the input. So he need check that part only..

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.