简体   繁体   中英

Javascript append array to array of object

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?

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
    });

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
    }
);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM