如何使用以下json数据创建嵌套数组

时间:2018-09-23 22:24:49

标签: javascript jquery arrays json frontend

我想使用以下json数据创建嵌套数组,但是有一个错误,我无法修复。我用jsfiddle创建了一个示例。这是我的js示例和下面的代码;

http://jsfiddle.net/r63oxcsk/

我想要实现的结果如下;

名称:


姓:
垂饰
哈里斯
坎贝尔

var Message = [
{
  "OrgID": "11",
  "OrgName": "Name:",
  "orgComboInfo": [
    {
      "OrgID": "11_8",
      "OrgName": "Don",
    },
    {
      "OrgID": "11_15",
      "OrgName": "Joan",
    }
  ]
},
{
  "OrgID": "12",
  "OrgName": "Surname:",
  "orgComboInfo": [
    {
      "OrgID": "12_2699",
      "OrgName": "Draper",
      "OrgType": "12"
    },
    {
      "OrgID": "12_2703",
      "OrgName": "Harris",
    },
    {
      "OrgID": "12_2666",
      "OrgName": "Campbell",
    }
   ]
 }
]

$( document ).ready(function() {
 var arrayB = [];
 var arrayA = [];

 for (var i=0; i<Message.length; i++) {
     var name = Message[i].OrgName;
     arrayA.push(name);

        for (var j=0; j < Message[i].orgComboInfo.length; j++) {
           var surname = Message[i].orgComboInfo[j].OrgName;
                arrayB.push(surname);
        }

        var total = arrayA.concat(arrayB);
        console.log(total);
   }
 })

1 个答案:

答案 0 :(得分:2)

您可以将顶级数组简化为属性名称为OrgName的对象,该对象是从orgComboInfo数组映射到OrgName的数组。

Reduce从一个空对象{}开始,并且每次迭代都使用新的属性OrgName传播上一次迭代的结果,该属性名为OrgName,这是仅映射到OrgName的orgComboInfo数组。

var Message = [
{
  "OrgID": "11",
  "OrgName": "Name:",
  "orgComboInfo": [
    {
      "OrgID": "11_8",
      "OrgName": "Don",
    },
    {
      "OrgID": "11_15",
      "OrgName": "Joan",
    }
  ]
},
{
  "OrgID": "12",
  "OrgName": "Surname:",
  "orgComboInfo": [
    {
      "OrgID": "12_2699",
      "OrgName": "Draper",
      "OrgType": "12"
    },
    {
      "OrgID": "12_2703",
      "OrgName": "Harris",
    },
    {
      "OrgID": "12_2666",
      "OrgName": "Campbell",
    }
   ]
 }
]

console.log(
    Message.reduce((result, item) => ({...result, [item.OrgName]: item.orgComboInfo.map(i => i.OrgName) }), {})
);