Vicheanak
Vicheanak

Reputation: 6684

Underscore Equivalent to Javascript For Loop?

I'd like to convert this code:

for (var i = 0; i < product.ages.length; i ++){
    for (var j = 0; j < $scope.ages.length; j ++){
        if (product.ages[i].id == $scope.ages[j].id){
            $scope.ages[j]['ticked'] = true;
        }
    }
}

into underscore.js. please help.

Upvotes: 0

Views: 102

Answers (4)

Gruff Bunny
Gruff Bunny

Reputation: 27976

Another way to solve this problem would be to first create a hash of the scope.ages using underscore's indexBy:

var scope_ages = _.indexBy($scope.ages, 'id');

The object would look something like:

{
    1: ref to scope.ages with id 1,
    2: ref to scope.ages with id 2,
    etc.
}

Then iterate over the product ages using each to set the ticked value:

_.each(product.ages, age => scope_ages[age.id].ticked = true)   

var product = {
	ages: [
		{ id : 1 }
	]
}

var $scope = {
	ages: [
		{ id : 0, ticked: false },
		{ id : 1, ticked: false },
		{ id : 2, ticked: false },
	]
}

var scope_ages = _.indexBy($scope.ages, 'id');

_.each(product.ages, age => scope_ages[age.id].ticked = true)

document.getElementById('scope_ages').textContent = JSON.stringify(scope_ages);
document.getElementById('result').textContent = JSON.stringify($scope.ages);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>

<h1>scope_ages</h1>
<p>
    <pre id="scope_ages"></pre>
</p>
<h1>Scope</h1>
<p>
  <pre id="result"></pre>
</p>

Upvotes: 1

Rajesh
Rajesh

Reputation: 24915

You can use _.find

_.each($scope.ages, function(v){
  v.ticked = _.find(product.ages, function(a){
    return v.age === a.age;
  })?true:false;
})

Also, just a pointer, you should use break on match.

Upvotes: 0

Damon
Damon

Reputation: 4336

This would be your code in underscore:

_.each(product.ages, function(pAge) {
  _.each($scope.ages, function(sAge) {
    if (pAge.id === sAge.id) {
      sAge.ticked = true;
    }
  });
});

Upvotes: 1

curtainrising
curtainrising

Reputation: 249

Here is an example on how you do an _.each on an object.

var example = {"hello":"world", "this":"is", "super":"neat"};
_.each(example, function(value, index){
  console.log(index + ":" + value);
}
->hello:world
->this:is
->super:neat

Upvotes: 0

Related Questions