0

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.

2
  • 2
    A for-loop like iteration would be _.each. Commented Jul 10, 2016 at 5:04
  • It's a shame there isn't an easily accessible list of Underscore methods that you could've consulted. Oh, wait... Commented Jul 10, 2016 at 8:03

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
  });
});

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.