-3

I've looked around and haven't found an specific answer here, but how would I access and update an object that is within an object?

In my example, how would I BJ.o[0]["todo-items"].length to the position of '33' in the data object.

BJ.o = o[0]["todo-items"].length;

var data = {
  datasets: [{
    data: [ 33, 9, 24, ],
    backgroundColor: [ "#FF6384", "#4BC0C0", "#FFCE56", ],
    label: 'My dataset' // for legend
  }],
  labels: [ "Overdue", "Today", "Upcoming", ]
};
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

3 Answers3

1
data.datasets[0].data[0]=BJ.o;

Using the assignment operator (=);

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

To your first question, this should be your solution:

data.datasets[0].data[0] = 50;

or

data.datasets[0].backgroundColor[0] = '#000000';

You may ask why I access some objects with [0] and others with just its name? That's because {data: ...} is an object itself so you can access it directly as it is, but if you have [{data: ...}, {data2: ...}] then you got an array so before accessing its children, you need to simply index them.

Here's a jsfiddle for you: https://jsfiddle.net/zavpdLpo/

JS:

var data = {
datasets: [{
    data: [
        33,
        9,
        24,
            ],
    backgroundColor: [
        "#FF6384",
        "#4BC0C0",
        "#FFCE56",
            ],
    label: 'My dataset' // for legend
}],
labels: [
    "Overdue",
    "Today",
    "Upcoming",
    ]
};

document.write(data.datasets[0].data[0]); // Prints 33
data.datasets[0].data[0] = 50;
document.write(data.datasets[0].data[0]); // Prints 50

HTML:

<div id="test"></div>

Hope this helps.

Giuseppe P.
  • 48
  • 2
  • 6
0

var data = {
    datasets: [{
        data: [
            33,
            9,
            24,
],
        backgroundColor: [
            "#FF6384",
            "#4BC0C0",
            "#FFCE56",
],
        label: 'My dataset' // for legend
    }],
    labels: [
        "Overdue",
        "Today",
        "Upcoming",
]
};
console.log(data.datasets[0].data[0])
// data.datasets[0].data[0] = whatever you want
Lucas Ricoy
  • 163
  • 1
  • 8