Javascript attaches an array to an array of an object

I tried adding a new value to a predefined array of objects as follows:

$scope.chartConfig.series.push(
    [{
        name: "Brands",
        colorByPoint: true,
        data: []
    }]
);

I want to add a new array value similar to this in data, but continue to fail. I tried:

$scope.todayChartConfig.series['data'] = [];
$scope.todayChartConfig.series['data'].push(
    {
        name: "Internet Explorer",
        y: 56.33
    },
    {
        name: "Chrome",
        y: 30.12
    }
);

But it joins the new object instead of merging with the current data array.

I expect:

[{
  name: "Brands",
  colorByPoint: true,
  data: [
    {
        name: "Internet Explorer",
        y: 56.33
    },
    {
        name: "Chrome",
        y: 30.12
    }
  ]
}]

How can i achieve this?

+4
source share
3 answers

With your current data structure, this should be:

$scope.todayChartConfig.series[0][0].data.push(
    {
        name: "Internet Explorer",
        y: 56.33
    },
    {
        name: "Chrome",
        y: 30.12
    }
);

What should work because:

$scope.chartConfig.series.push(
    [{
        name: "Brands",
        colorByPoint: true,
        data: []
    }]
);

pushes an array of an object into an array.

However, if the code above is a typo and what you really intended:

$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
    }
);
+2
source

, todayChartConfig.series - , $scope.todayChartConfig.series[0].

, . ( . . )

, :

$scope.todayChartConfig.series[0]['data']
   .push({
        name: "Internet Explorer",
        y: 56.33
    }).push({
        name: "Chrome",
        y: 30.12
    });

. (. @slebetman ). ,

$scope.todayChartConfig.series[0]['data']
.push({
        name: "Internet Explorer",
        y: 56.33
    },
    {
        name: "Chrome",
        y: 30.12
    });
+2

- $scope.chartConig.series, $scope.todayChartConfig.series. , .

:

$scope.chartConfig.series['data'] = [];
$scope.chartConfig.series['data'].push(
    {
        name: "Internet Explorer",
        y: 56.33
    },
    {
        name: "Chrome",
        y: 30.12
    }
);

, , . jsFiddle

+1

Source: https://habr.com/ru/post/1625934/


All Articles