这段代码在创建等效的 javascript 对象时有什么问题?

What is wrong with this code in creating an equivalent javascript object?

这是原始 javascript 对象;

$scope.XXXChart.options =
{
    'title': '10-year (%)',    
    'hAxis': {
        'title': "Date",
        'format': "MMM-yyyy",
    },    
    'explorer': {      
        actions: ['dragToZoom', 'rightClickToReset'],
        maxZoomIn: 0.01,
        axis: 'horizontal',
        keepInBounds: true,
    }
}; 

我想用以下内容制作一个等效对象;

    var common_Chart_options =
    {
        'hAxis': {
            'title': "Date",
            'format': "MMM-yyyy",
        },
        'explorer': {
            //actions: ['dragToPan', 'rightClickToReset'],
            actions: ['dragToZoom', 'rightClickToReset'],
            maxZoomIn: 0.01,
            axis: 'horizontal',
            keepInBounds: true,
        }
    };

$scope.XXXChart.options =
    {
        'title': '10-year (%)', 
        common_Chart_options 
    }
};

这段代码有什么问题?没有错误消息,但 Google 图表缩放功能停止工作。

手动合并对象。 尝试:

$scope.XXXChart.options =
{
    'title': '10-year (%)', 
    'hAxis': common_Chart_options.hAxis,
    'explorer': common_Chart_options.explorer
}

或:

$scope.XXXChart.options =
{
    'title': $scope.XXXChart.options.title
    'hAxis': {
        'title': "Date",
        'format': "MMM-yyyy",
    },
    'explorer': {
        //actions: ['dragToPan', 'rightClickToReset'],
        actions: ['dragToZoom', 'rightClickToReset'],
        maxZoomIn: 0.01,
        axis: 'horizontal',
        keepInBounds: true,
    }
};

否则使用像 underscore.extend.

这样的合并

在 ES5 及更早版本中,这是一个语法错误:

$scope.XXXChart.options =
    {
        'title': '10-year (%)', 
        common_Chart_options      // <=== Here
    }
};

属性 初始值设定项后必须有一个冒号和一个值。

在 ES2015+ 中,这会在名为 common_Chart_options 的对象上创建一个 属性。它不会common_Chart_options的属性合并到您正在创建的对象中。

您可以使用 extend:

$scope.XXXChart.options = angular.extend(
    {},
    {
        'title': '10-year (%)'
    },
    common_Chart_options
);

我以前做过类似的事情,我通过用 this answer.

中的函数合并两个对象解决了这个问题

函数看起来像

function merge_options(obj1,obj2){
 var obj3 = {};
 for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
 for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
 return obj3;
}

我用过它

var standardOptions = {height:700,width:500};
var customOptions = {height:500, title:'TestingTitles'};
var finalOptions = merge_options(standardOptions, customOptions);

最后的选项将导致

{height:500, width:500, title:'TestingTitles'}