I tried to add new value to a pre-defined array of object like this:
$scope.chartConfig.series.push(
[{
name: "Brands",
colorByPoint: true,
data: []
}]
);
I want to add a new array value like so to data but keep failing. I've tried:
$scope.todayChartConfig.series['data'] = [];
$scope.todayChartConfig.series['data'].push(
{
name: "Internet Explorer",
y: 56.33
},
{
name: "Chrome",
y: 30.12
}
);
But it append to a new object instead of combine with the current data array.
What I expect is:
[{
name: "Brands",
colorByPoint: true,
data: [
{
name: "Internet Explorer",
y: 56.33
},
{
name: "Chrome",
y: 30.12
}
]
}]
How can I achieve that?
3 Answers 3
With your current data structure it should be:
$scope.todayChartConfig.series[0][0].data.push(
{
name: "Internet Explorer",
y: 56.33
},
{
name: "Chrome",
y: 30.12
}
);
Which should work because:
$scope.chartConfig.series.push(
[{
name: "Brands",
colorByPoint: true,
data: []
}]
);
pushes an array of object into an array.
However, if the above code is a typo and what you really intended was:
$scope.chartConfig.series.push(
{
name: "Brands",
colorByPoint: true,
data: []
}
);
then it should be:
$scope.todayChartConfig.series[0].data.push(
{
name: "Internet Explorer",
y: 56.33
},
{
name: "Chrome",
y: 30.12
}
);
The first issue is that todayChartConfig.series is an array so you should be appending to $scope.todayChartConfig.series[0].
The second issue is that you need to append the objects individually. (Not true. See edit below)
So, this should work:
$scope.todayChartConfig.series[0]['data']
.push({
name: "Internet Explorer",
y: 56.33
}).push({
name: "Chrome",
y: 30.12
});
Edit: You can also append the objects all together (see @slebetman's comment below). So, this works too
$scope.todayChartConfig.series[0]['data']
.push({
name: "Internet Explorer",
y: 56.33
},
{
name: "Chrome",
y: 30.12
});
3 Comments
Array.push() actually can accept multiple argumentsdata = []. So, data.push([1, 2]) results in [[1, 2]] and not [1,2]. Sounds like @SSuhat wants the latter and not the former hence the requirement to push individually.data.push(1,2) not data.push([1,2])Your original array is $scope.chartConig.series, and then you're pushing onto $scope.todayChartConfig.series. Your problem is that you're not pushing onto the correct array.
You need to do:
$scope.chartConfig.series['data'] = [];
$scope.chartConfig.series['data'].push(
{
name: "Internet Explorer",
y: 56.33
},
{
name: "Chrome",
y: 30.12
}
);
To do what you want to do, see this jsFiddle
$scope.todayChartConfig.series[0][0].data.push(...)but I'm not sure if you really intended that 2D arrayseriesproperty is an array of arrays of objects. But in your second example,seriesappears to be an object that you're trying access a property on.