【问题标题】:Build object w/ multi dimensional arrays to dynamically create columns使用多维数组构建对象以动态创建列
【发布时间】:2021-09-28 02:05:46
【问题描述】:

所以我想看看是否有人可以引导我朝着正确的方向前进。所以我想用多维数组构建一个对象,所以我有三个主要的东西需要分组:“Categories”、“Subheading”、“NoSubHeading”。

这是data.d.results的API响应。

我将它定义为var obj = Object.assign({}, data.d.results);的对象

所以我想构建这样的东西:

{
  "Category": {
    "Some Subheading": [
      somepost,
      someotherpost
    ],
    "Some Other Subheading": [
      anotherpost,
      blah
    ],
    "No Subheading": [
      anotherpost,
      blah
    ]
  },
  "Another Category": {
    "Some Subheading": [
      somepost,
      someotherpost
    ],
    "Some Other Subheading": [
      anotherpost,
      blah
    ]
  }
}

如果有人能引导我朝着正确的方向前进,我们将不胜感激!

【问题讨论】:

    标签: javascript jquery arrays object


    【解决方案1】:

    在迭代对象时使用子标题来定义你的数组:

    // Initialize output
    var result = {};
    
    for (var i = 0; i < obj.length; i++) {
    
      // Retrieve values
      var cat = obj[i].Category;
      var sub = obj[i].Subheading;
    
      // Check empty subheading condition
      if (!sub || sub == "") sub = "No Subheading";
    
      // Initialize objects
      if (result[cat] === undefined) result[cat] = {}; // Empty object
      if (result[cat][sub] == undefined) result[cat][sub] = []; // Empty array
    
      // Insert element at the position defined by Category on the
      // first layer object, and defined by Subheading on the second layer array
      result[cat][sub].push(obj[i]);
    }
      
    

    【讨论】:

    • 爱丽儿这太棒了!非常感谢!我如何能够.append() 构建一些 HTML 来传递数据?
    猜你喜欢
    • 2014-08-14
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多