【问题标题】:how to create nested arrays using the following json data如何使用以下 json 数据创建嵌套数组
【发布时间】:2019-02-27 11:02:20
【问题描述】:

我想使用以下 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);
   }
 })

【问题讨论】:

    标签: javascript jquery arrays json frontend


    【解决方案1】:

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

    Reduce 从一个空对象 {} 开始,每次迭代都会使用一个名为 OrgName 的新属性传播上一次迭代的结果,该属性是映射到仅 theOrgName 的 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) }), {})
    );

    【讨论】:

    • 我已经编辑了答案以使用 reduce 成为你想要的形状
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2018-11-27
    • 2022-12-19
    • 2021-08-24
    相关资源
    最近更新 更多