通过嵌套数组项使用underscorejs来平面化数组

时间:2016-01-13 12:48:13

标签: javascript underscore.js

我有对象数组,每个对象都有列表,每个嵌套列表包含1和2。

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

我希望通过下划线创建dupplicted list,如下所示:

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

怎么办?

2 个答案:

答案 0 :(得分:2)

您也可以在没有underscore.js的情况下执行此操作。以下是纯粹的js版本:

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

答案 1 :(得分:1)

以下是我用下划线尝试的方式。

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

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

对于数组中的每个对象,使用splitCompany根据companies数据创建并返回两个对象,然后展平返回的数组。

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

DEMO