How to dynamically create an object property?

2

I'm currently doing this, but error occurs when giving build to the project:

function AddSelectOption(name, item) {
    vm.item = {
         name: item["name"],
         [name]: item[name] //Erro nessa linha
    };
    vm.filters[name].push(vm.item);
}

//call   AddSelectOption('statusID',$item)
    
asked by anonymous 24.02.2017 / 17:14

3 answers

4

Just add the property after creating the object using the ['propriedade'] syntax.

function AddSelectOption(name, item) {
    vm.item = {
    };

    vm.item[name] = item;

    vm.filters[name].push(vm.item);
}
    
24.02.2017 / 17:21
2

To create something dynamic can be solved with eval :

var app = angular.module('app', []);
app.controller('ctrl', ['$scope', function($scope)
{
  var vm = $scope;
  vm.filters = [];
  vm.AddSelectOption = function(name, item) 
  {   
    var item = eval("item = {"+name+":"+item+"}");    
    vm.filters.push(item);
  }
  
  vm.load = function()
  {
    vm.AddSelectOption('key1',1);
    vm.AddSelectOption('key2',2);
    vm.AddSelectOption('key3',3);
    console.log(vm.filters);
  }  
  vm.load();
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
</div>
    
24.02.2017 / 17:40
2

Confirm that $item has a name property.

Dynamic creation of computed properties works perfectly in most modern browsers:

// Computed property names (ES2015)

function AddSelectOption(name, item) {
    var item = {
         name: item,
         [name]: item
    };
    
console.log(item);
}

AddSelectOption('statusID','teste');

Expected result:

{
  "name": "teste",
  "statusID": "teste"
}
    
24.02.2017 / 18:00