0

I have the following data object

var data = {
  labels: ["2013", "2014", "2015", "2016"],
  datasets: [
    {
      label: "Label 1", 
      data: data1,
    }, 
    {
      label: "Label 2", 
      data: data2, 
    }
  ]
};

I want to get the second label "Label 2".

I have tried to use

console.log(data.datasets[0].label); // Only returns Label 1
console.log(data.datasets[0][1].label); // Doesn't work

I don't want to make changes on the structure as I am using it with Chart.js to draw charts.

Thanks in advance.

1
  • 2
    console.log(data.datasets[1].label); ..? Commented May 13, 2016 at 10:04

2 Answers 2

3

You can access it like this:

console.log( data.datasets[1].label );

Example: https://jsfiddle.net/55ex0p80/

Let's break it down into four steps:

data.datasets[ 1 ].label
|    |         |  |
1    2         3  4
|    |         |  \- The field "label" of the object
|    |         \---- The desired key of the array called "datasets"
|    \-------------- The array called "datasets"
\------------------- The data object

This way you end up at the label field you were looking for:

var data = {             <---- step 1
  labels: ["2013", "2014", "2015", "2016"],
  datasets: [            <---- step 2
    {
      label: "Label 1", 
      data: data1,
    }, 
    {                    <---- step 3
      label: "Label 2",  <---- step 4
      data: data2, 
    }
  ]
};
Sign up to request clarification or add additional context in comments.

Comments

1
  • data = {} is an object
  • labels =["2013","2014",...] is an array of strings
  • datasets = [{},{},{}] is an array of objects

Thus for accessing 'Label 2' you need to access 2nd object of the datasets array and then access its label as: data.datasets[1].label

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.