How to create a property of an object dynamically?

Asked

Viewed 1,104 times

2

I’m currently doing it this way, but it occurs error in giving build in 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)
  • What is the name of the property you want to create?

  • @jbueno I edited the question.

  • @Matheus you want to add an item to a list?

  • 1

    @Virgilionovic That, where this item in one of its properties, has to be created dynamically.

3 answers

4


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

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

    vm.item[name] = item;

    vm.filters[name].push(vm.item);
}
  • And there is another way more "elegant" or that gets leaner without having to create the vm.?

2

Confirm that $item owns a property name.

Dynamic creation of computed properties works perfectly on 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"
}

1

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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.