1

I have array of objects that each object have list and each nested list contain 1 and 2.

[{
    "name":"a",
    "companies":[1,2]
},
{
    "name":"b",
    "companies":[1,2]
},
{
    "name":"c",
    "companies":[1,2]
}]

I want create dupplicted list by underscorejs like this:

[{
    "name":"a",
    "company":1
},
{
    "name":"a",
    "company":2
},
{
    "name":"b",
    "company":1
},
{ 
    "name":"b",
    "company":2
},
{
    "name":"c",
    "company":1
},
{
    "name":"c",
    "company":2
}]

How can do it?

2 Answers 2

2

You can do this without underscore.js as well. Following is a pure js version:

var data = [{
    "name":"a",
    "companies":[1,2]
},
{
    "name":"b",
    "companies":[1,2]
},
{
    "name":"c",
    "companies":[1,2]
}];

var result = [];
data.forEach(function(item){
  item.companies.forEach(function(company){
    result.push({"name": item.name, "company": company});
  });
});

console.log(result);

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

Comments

1

Here's how I've attempted it with underscore.

function makeCompany(name) {
  return function (company) {
    return { name: name, companies: company };
  }
}

function splitCompany(obj) {
  return _.map(obj.companies, makeCompany(obj.name));
}

For each object in the array, use splitCompany to create and return two objects based on the companies data, then flatten the returned array.

var result = _.flatten(_.map(arr, splitCompany));

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.