附加到Typescript中的对象变量

时间:2018-05-10 06:56:12

标签: javascript typescript

最终,我想创建一个对象:

newData = {
    column1: "",
    column2: "",
    column3: "",
    ...
    columnN: ""
}

列名来自另一个对象数组,它本质上是一个全局变量tableColumns:

tableColumns = [
    {headerName: "column1", field: "c1", editable: false},
    {headerName: "column2", field: "c2", editable: false},
    {headerName: "column3", field: "c3", editable: false},
    {headerName: "column4", field: "c4", editable: false}
]

没有任何硬编码,如何通过循环遍历this.tableColumns动态创建newData?

2 个答案:

答案 0 :(得分:1)

循环$scope.submit = function(employees) { $http({ 'url' : '/updateOverride', 'method' : 'POST', 'headers' : { 'Content-Type' : 'application/json' }, 'data' : $scope.employees }).then(function(employees) { $scope.insertResult = employees.data; var controllerMessage = $scope.insertResult; var messageKey = 'result'; var result = controllerMessage[messageKey]; console.log(controllerMessage); if(result == "success"){ } else { var dataKey = 'data'; var policyData = controllerMessage[dataKey]; $scope.policyNumber = policyData; console.log($scope.policyNumber); } $("#alert_"+result).show() }) }; 并将tableColumns键的值设置为headerName对象的键:



newData




答案 1 :(得分:0)

循环浏览您的商品,并根据您的headerName

动态分配属性



const tableColumns = [
    {headerName: "column1", field: "c1", editable: false},
    {headerName: "column2", field: "c2", editable: false},
    {headerName: "column3", field: "c3", editable: false},
    {headerName: "column4", field: "c4", editable: false}
];

const result = {};

tableColumns.forEach(item => {
  result[item.headerName] = item.field;
});

console.log(result);