1

Im kinda getting into functional programming. My problem it is about how you can map information from nested data.

I have an array of companies.

[  
  {
    _id: 123,
    name: "Company"
  }, 
  {
    _id: 789,
    name: "Company"
  }
];

I have an array of teams.

[  
  {
    _id: 555,
    name: "Team name A",
    companyId: 123
  }, 
  {
    _id: 666,
    name: "Team name B",
    companyId: 123
  },
  {
    _id: 777,
    name: "Team name C",
    companyId: 789
  }
];

I would like to put teams into company object for every company. The expect result would be:

[  
  {
    _id: 123,
    name: "Company",
    teams: [  
             {
               _id: 555,
               name: "Team name A",
               companyId: 123
             }, 
             {
               _id: 666,
               name: "Team name B",
               companyId: 123
             }
           ]
  }, 
  {
    _id: 789,
    name: "Company",
    teams: [  
             {
               _id: 777,
               name: "Team name A",
               companyId: 789
             }
           ]
  }
];

My solution has been to do it in several steps:

teamsGroupedByCompany = _.group(teams, 'companyId');

var findTeamsByCompanyId = function(groupedTeams, companyId){
    return _.chain(groupedTeams)
            .find(function(value, key){
               return companyId == key;
            })
            .flatten()
            .defaults([])
            .value();
}

_.map(companies, function(company){
    company.team = findTeamsByCompanyId(teamsGroupedByCompany, company._id);
})

Can it be done in a chaining way or I have to make higher order functions to deal with these kind of issues? Currently Im using lodash.

Here is the jsbin https://jsbin.com/buqiji/edit?js,console

2 Answers 2

1

The following code will do the trick.

companies = _.chain(companies)
.map(function(company) {
  company.teams = _.filter(teams, {'companyId': company._id});
  return company;
})
.value();

Here's a JsBin: https://jsbin.com/cudoheziyi/1/edit?js,console

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

Comments

1

My solution is similar to yours. I'm doing it in two steps as well.

You already have teamsGroupedByCompany so you can use that to assign teams to each company directly without having to do findTeamsByCompanyId. Here's my solution:

(assume companies and teams are already initialized)

const groupedTeams = _.groupBy(teams, 'companyId');
const combined = _.map(companies, c => {
  c.teams = groupedTeams[c._id] || [];
  return c;
});

http://jsbin.com/mixewo/1/edit?js,console

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.