动态地向现有对象添加对象属性

Dynamically add an object property to existing object

本文关键字:对象 添加 属性 动态      更新时间:2023-09-26

我有一个json对象,如:

"highChart":{
            "xAxis":{  
               "categories":[  
                  "SYN 13 ",
                  "Settlement",
                  "Service Interaction",
                  "FNOL",
                  "Repair Process",
                  "Rental Experience",
                  "Appraisal",
                  "SYN 14 "
               ],
               "title":{  
                  "text":""
               },
               "labels":{  
                  "enabled":true,
                  "maxStaggerLines":1
               },
               "tickWidth":1
            }}

我们把它定义为$scope.chartConfig = highChart

现在我想给chartConfig添加另一个属性,像这样:

"highChart":{
         "options":{
            "chart":{  
               "height":null,
               "type":"waterfall"
            }},
            "xAxis":{  
               "categories":[  
                  "SYN 13 ",
                  "Settlement",
                  "Service Interaction",
                  "FNOL",
                  "Repair Process",
                  "Rental Experience",
                  "Appraisal",
                  "SYN 14 "
               ],
               "title":{  
                  "text":""
               },
               "labels":{  
                  "enabled":true,
                  "maxStaggerLines":1
               },
               "tickWidth":1
            }}

因此,在初始化$scope.chartConfig = highChart之后,我想添加options属性以及上图所示的chart属性。我怎么做呢?

就像这样…

$scope.chartConfig.options = {
  "chart":{  
    "height":null,
    "type":"waterfall"
 }
};

不是100%清楚你在问什么,但你可以使用angular.extend()来合并对象

var options = {
    "chart": {
        "height": null,
        "type": "waterfall"
    }
}
angular.extend($scope.chartConfig, options);

$scope.chartConfig现在包含新的属性。如果options有一些属性是相同的原始但不同的值…原来的将被更新为这些值