合并具有空值的数组项

时间:2017-05-23 07:57:38

标签: javascript jquery arrays

我有一个包含来自不同表的数据的数组(至少9个表)。我想迭代数组并以一种方式合并它们,第一项是从所有数组中获取,然后是第二项,依此类推。

我现在用下面的例子更好地解释一下。

假设我有一个如下所示的输入数组:



var arrData = [{
    "Id": 1,
    "Name": 'Ken',
    "Age": '',
    "Hobbies": [{
      'HobbyId': 1,
      'HobbyName': 'Swimming'
    }, {
      'HobbyId': 2,
      'HobbyName': 'Reading'
    }],
    "Skills": [{
      'SkillId': 1,
      'SkillName': 'PHP'
    }, {
      'SkillId': 2,
      'SkillName': 'MySQL'
    }],
    "Language": [{
      'LangId': 2,
      'LangName': 'English'
    }, {
      'LangId': 3,
      'LangName': 'Chinese'
    }]
  },
  {
    "Id": 2,
    "Name": 'Mike',
    "Age": '20',
    "Hobbies": [],
    "Skills": [],
    "Language": []
  },
  {
    "Id": 3,
    "Name": 'Charlie',
    "Age": '25',
    "Hobbies": [{
      'HobbyId': 5,
      'HobbyName': 'Dance'
    }, {
      'HobbyId': 6,
      'HobbyName': ''
    }, {
      'HobbyId': 7,
      'HobbyName': 'Writing'
    }],
    "Skills": [],
    "Language": [{
      'LangId': 7,
      'LangName': 'English'
    }]
  }
];

console.log(arrData);




我的结果数组应如下所示:

[
    [1,"Ken",'',1,'Swimming',1,'PHP',2,'English'],
    [1,"Ken",'',2,'Reading',2,'MySQL',3,'Chinese'],
    [2,"Mike",'20','','','','','',''],
    [3,"Charlie",'25','5','Dance','','',7,'English'], 
    [3,"Charlie",'25','6','','','','',''], 
    [3,"Charlie",'25','7','Writing','','','',''], 
]

在这里您可能会注意到项目的循环迭代该项目的数组中找到的最大次数。 因此,对于Id = 3且名称=' Charlie'循环迭代3次,因为在Hobbies数组中有3个(最大)项。

这只是一个示例数组,实际上我将有9个数组,我的代码应该非常动态来处理它。

我已经实现了90%的输出但是我只是在应该为数组中找不到的项传递空值的地方。 例如,在上面的示例中,Mike没有爱好,技能或语言的项目,在这种情况下,我仍然需要传递空值。 或者,如果你看到查理有3个爱好,没有技能和1个语言,我的数组应该有3个项目,但是因为技能是空的,它们应该有空值,对于查理的第二个和第三个项目它应该有空值的语言

我希望这是有道理的。

我已尝试过如下代码,我将在底部解释。



$(function() {
  // Handler for .ready() called.

  var finalData = [],
    arr = [],
    arrHeader = [],
    cnt = 0,
    generateMaxRows = 0;
  //finalData.push({"Id":"","Name":'',"Age" : '','HobbyId':'Hobbies','HobbyName':'', 'SkillId':'Skills','SkillName':'','LangId':'Language','LangName':''});

  var arrHeader = [{
    "Id": "Id",
    "Name": 'Name',
    "Age": 'Age',
    "Hobbies": [{
      'HobbyId': 'HobbyId',
      'HobbyName': 'HobbyName'
    }],
    "Skills": [{
      'SkillId': 'SkillId',
      'SkillName': 'SkillName'
    }],
    "Language": [{
      'LangId': 'LangId',
      'LangName': 'LangName'
    }]
  }];
  var arrData = [{
      "Id": 1,
      "Name": 'Ken',
      "Age": '',
      "Hobbies": [{
        'HobbyId': 1,
        'HobbyName': 'Swimming'
      }, {
        'HobbyId': 2,
        'HobbyName': 'Reading'
      }],
      "Skills": [{
        'SkillId': 1,
        'SkillName': 'PHP'
      }, {
        'SkillId': 2,
        'SkillName': 'MySQL'
      }],
      "Language": [{
        'LangId': 2,
        'LangName': 'English'
      }, {
        'LangId': 3,
        'LangName': 'Chinese'
      }]
    },
    {
      "Id": 2,
      "Name": 'Mike',
      "Age": '20',
      "Hobbies": [],
      "Skills": [],
      "Language": []
    },
    {
      "Id": 3,
      "Name": 'Charlie',
      "Age": '25',
      "Hobbies": [{
        'HobbyId': 5,
        'HobbyName': 'Dance'
      }, {
        'HobbyId': 6,
        'HobbyName': ''
      }, {
        'HobbyId': 7,
        'HobbyName': 'Writing'
      }],
      "Skills": [],
      "Language": [{
        'LangId': 7,
        'LangName': 'English'
      }]
    }
  ];


  jQuery.each(arrData, function(key, val) {
    arr = [];
    generateMaxRows = 1;
    jQuery.each(val, function(k, v) {
      if (Array.isArray(v)) {
        generateMaxRows = (v.length > generateMaxRows) ? v.length : generateMaxRows;
      }
    });

    for (var row = 0; row < generateMaxRows; row++) {
      arr = [];
      jQuery.each(arrHeader[0], function(header_key, header_val) {

        jQuery.each(val, function(row_key, row_val) {
          if (row_key == header_val) // Not an array.
          {
            arr.push(row_val);
          } else {
            if (Array.isArray(header_val)) {
              if (Array.isArray(row_val)) {
                jQuery.each(header_val[0], function(head_key, head_val) {
                  console.log(head_val);
                  jQuery.each(row_val[row], function(subrow_key, subrow_val) {
                    if (subrow_key == head_val) {
                      arr.push(subrow_val);
                    }
                  });

                });
              }
            }
          }
        });

        //   console.log(arr);

      });
      finalData.push(arr);
    }
  });

  console.log(JSON.stringify(finalData));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我做了一个静态数组arrHeader,它将定义要与输入数组进行比较的数组项。

我已经实现了90%的输出,除了我必须传递空值的地方arrHeader有一个项目但arrData没有。

下面是我的实例助手数组(arrHeader)。

var arrHeader= {
        "ItemMasterNumber": "ItemMasterNumber",
        "IM_Description": "IM_Description",
        "IM_FirstProcessDate": "IM_FirstProcessDate",
        "IM_Alias": "IM_Alias",
        "IM_MasterPrice": "IM_MasterPrice",
        "IM_Category": "IM_Category",
        "IM_Version": "IM_Version",
        "IM_Type": "IM_Type",

        "ItemProducts" : [{
        "PO_Id" : "PO_Id",
        "PO_Code" : "PO_Code",
        "PO_Name" : "PO_Name",
        "PO_Type" : "PO_Type",
        "PO_TaxClassification" : "PO_TaxClassification",
        "PO_Bundle" : "PO_Bundle",
        "PO_PricingMechanism" : "PO_PricingMechanism",
        "PO_StoreVisible" : "PO_StoreVisible",
        "PO_NotSoldSeparately" : "PO_NotSoldSeparately",
        "PO_EnableDate" : "PO_EnableDate",
        "PO_AvailaibilityRule" : "PO_AvailaibilityRule",
        "PO_DisableDate" : "PO_DisableDate",
        "PO_MinOrderQty" : "PO_MinOrderQty",
        "PO_ExpectedReleaseDate" : "PO_ExpectedReleaseDate",
        "PO_Description" : "PO_Description",
        "PO_GrantOfferingType" : "PO_GrantOfferingType"
        }],

        "ItemFeatureSet": [{
                "FS_Id": "FS_Id",
                "FS_Code": "FS_Code",
                "FS_Name": "FS_Name",
                "FS_Description": "FS_Description",
                "FS_EnablementType": "FS_EnablementType"
            }],
        "ItemFeatures": [{
                "FE_Id": "FE_Id",
                "FE_Name": "FE_Name",
                "FE_Value": "FE_Value"

            }],
        "ItemCharges": [{
                "CH_ChargeId": "CH_ChargeId",
                "CH_Name": "CH_Name",
                "CH_Description": "CH_Description",
                "CH_Type": "CH_Type",
                "CH_ProvisioningTag": "CH_ProvisioningTag",
                "CH_Currency": "CH_Currency",
                "CH_CustomerSegment": "CH_CustomerSegment",
                "CH_ExtendedCustomerSegment": "CH_ExtendedCustomerSegment",
                "CH_Region": "CH_Region",
                "CH_Active": "CH_Active"

            }],
        "ItemChargeAttributes": [{
                "CA_Id": "CA_Id",
                "CA_ListPrice": "CA_ListPrice",
                "CA_FairValueBasis": "CA_FairValueBasis",
                "CA_FairValueMethod": "CA_FairValueMethod",
                "CA_FairValueLow": "CA_FairValueLow",
                "CA_FairValueHigh": "CA_FairValueHigh",
                "CA_EffectiveStartDate": "CA_EffectiveStartDate"
            }],
        "ItemPackages": [{
                "PA_PackageId": "PA_PackageId"
            }],
        "ItemPackagesComponents": [{
                "PA_ComponentId": "PA_ComponentId",
                "PA_Type": "PA_Type",
            }],
        "ItemOffers": [{
                "OF_OfferId": "OF_OfferId",
                "OF_Name": "OF_Name",
                "OF_Description": "OF_Description",
                "OF_Level": "OF_Level",
                "OF_Type": "OF_Type",
                "OF_CustomerSegment" : "OF_CustomerSegment",
                "OF_SalesChannel" : "OF_SalesChannel",
                "OF_ListPriceOffer" : "OF_ListPriceOffer",
                "OF_Region" : "OF_Region",
                "OF_CountryCode" : "OF_CountryCode",
                "OF_EffectiveStartDate": "OF_EffectiveStartDate",
                "OF_EffectiveEndDate": "OF_EffectiveEndDate"
            }],
        "ItemOffersComponents": [{
                "OC_Id": "OC_Id",
                "OC_Quantity": "OC_Quantity",
                "OC_AdjustmentAmount": "OC_AdjustmentAmount"
            }]
    };

你可以帮我解决这个问题吗? 很感谢任何形式的帮助。 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将arrHeader与数组一起用于嵌套属性。对于零,使用实际索引。

&#13;
&#13;
var arrHeader = [
        'Id',
        'Name',
        'Age',
        ['Hobbies', 0, 'HobbyId'],
        ['Hobbies',  0, 'HobbyName'],
        ['Skills',   0, 'SkillId'],
        ['Skills',   0, 'SkillName'],
        ['Language', 0, 'LangId'],
        ['Language', 0, 'LangName']
    ],
    data = [{ Id: 1, Name: "Ken", Age: "", Hobbies: [{ HobbyId: 1, HobbyName: "Swimming" }, { HobbyId: 2, HobbyName: "Reading" }], Skills: [{ SkillId: 1, SkillName: "PHP" }, { SkillId: 2, SkillName: "MySQL" }], Language: [{ LangId: 2, LangName: "English" }, { LangId: 3, LangName: "Chinese" }] }, { Id: 2, Name: "Mike", Age: "20", Hobbies: [], Skills: [], Language: [] }, { Id: 3, Name: "Charlie", Age: "25", Hobbies: [{ HobbyId: 5, HobbyName: "Dance" }, { HobbyId: 6, HobbyName: "" }, { HobbyId: 7, HobbyName: "Writing" }], Skills: [], Language: [{ LangId: 7, LangName: "English" }] }],
    result = data.reduce(function (r, a) {
        var max = arrHeader.reduce(function (m, k) {
                return Array.isArray(k) ? Math.max(m, (a[k[0]] || []).length) : m;
            }, 1),
            i;

        for (i = 0; i < max; i++) {
            r.push(arrHeader.map(function (k) {
                return Array.isArray(k) ? k.reduce(function (v, l) {
                    return (v || {})[l || i] || '';
                }, a) : a[k];
            }));
        }
        return r;
    }, []);

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;