Nolan
Nolan

Reputation: 916

Reset JS array and set dynamic key array with one line of code?

EDIT

The following question How do I empty an array in JavaScript? does not answer the question i.e. I get how to set / reset an array but that was not my question. I want to to do is:

  1. set the key with a dynamic value e.g. UUID and,
  2. then set element[0] (the above) to true in one line of code.

QUESTION

Code base: Angular 1.5x, lodash 4.x

Seems like a basic question but cannot find an answer. Is it possible using JS, Angular or lodash to reset an array and set it at the same time per the example below. As per the example below the array will keep pushing unless I set reset it. Why you ask, example if I'm using a UUID as key in the HTML e.g.

HTML

<li id="{[{contactus.app_id}]}"
    ng-show="view.state[item.uuid]"
    ng-repeat="item in collection.items track by item.uuid">
</li>

JS (Angular)

NOTE: this code works and I could also use replace $scope.view.state.length = 0; with $scope.view.state = []; but my question is more along the lines of reseting an array, adding a dynamic key and setting it to true all in one line of code. The complexity is in the dynamic key.

$scope.view = {state:[]};

$scope.setViewState = function (id) {
    // how can I collapse the following 2 lines of code into one
    $scope.view.state = [];
    $scope.view.state[id] = true;
};

Upvotes: 0

Views: 228

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159955

You can use computed properties to do this in one line:

$scope.view.state = {[id]: true};

However, this will only work on the latest browsers (Chrome, Firefox, Safari 7.1+, and Edge) and if you have any build steps that need to parse your code they will also need to be upgraded to understand the syntax as well.

If you need older browser support (or if your build tools cannot be upgraded) then you'll need to do it in two steps. However, you can hide those steps in a function:

function initialState(key, value) {
  var result = {};
  result[key] = value;
  return result;
}

then you can simply do:

$scope.view.state = initialState(id, true);

Upvotes: 1

Related Questions