Search code examples
javascriptbackbone.js

Backbone Collection get Object - Part 2


I asked this question earlier and need some more help.

The question: Backbone Collection get Object.

My problem is that the answer only gives me back the first object in the array. How would i get back all of them.

Pretty much, how would I take:

{
  "id" : "section-one",
  "href" : "section-one-baseball",
  "divisions" : [
    {
      "name": "Orioles",
      "division" : "AL East"
    }
  ]
}

Which I then got help being able to get the name from the divisions like this:

BaseballTeams.models[0].get("divisions.name")

Now what I need to do is be able to take multiple names from something like this:

{
 "id" : "section-one",
 "href" : "section-one-baseball",
 "divisions" : [
   {
     "name": "Orioles",
     "division" : "AL East"
   },
   {
     "name": "Yankees",
     "division": "AL East"
  ]
}

So instead of getting just the first one, I need to be able to get all of them from the divisions.

I am getting the results using underscore _.each to retrieve them.

Thank you in advance for your help


Solution

  • I know this has already been answered but just to add another option, underscore has a pluck method for just this use case, where you want to pluck an attribute from a list. you provied it the list then the name of the property you want to extract. It will then return an array of the property from each each item in the list.

    divisions = [{
        name: "Orioles",
        division: "AL East"
      }, {
        name: "Yankees",
        division: "AL East"
      }
    ]
    
    
    divisionNames = _.pluck(divisions, "name");
    
    console.log(divisionNames);
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>