【问题标题】:jQuery: Iterate through JSON object which has children and targeting them separatelyjQuery:遍历具有子对象并分别定位它们的 JSON 对象
【发布时间】:2021-06-23 08:22:20
【问题描述】:

我有一个 JSON 结构

{
  "sections": [
    {
      "name": "Section 1",
      "pre": "Pre text",
      "post": "Post text",
      "inputs": [
        {
          "text_01": "Evidence 01",
          "text_02": "Evidence 02",
          "textarea_01": "Evidence 03",
          "textarea_02": "Evidence 04"
        }
      ]
    },
    {
      "name": "Section 2",
      "pre": "Pre text lad",
      "post": "Post text bro",
      "inputs": [
        {
          "text_03": "Evidence 05",
          "text_04": "Evidence 06",
          "textarea_03": "Evidence 07",
          "textarea_04": "Evidence 08"
        }
      ]
    }
  ]
}

我必须遍历的 jQuery 是:

$.getJSON( "/training/assets/json/test.json", function( data ) {
  $.each( data["sections"], function( key, val ) {
    console.log('[+] Top Level');
    console.log(val["name"]);
    console.log(val["pre"]);
    console.log(val["post"]);

    console.log('[+] Inputs');
    $.each( val["inputs"], function( k, v ) {
      $.each( val["inputs"][k], function( ke, va ) {
        console.log(ke + ' - ' + va);
      });
    });
  });
}); 

这会吐出以下内容,这是我想要的,但我想知道是否有更清洁的方法来实现同样的目标?

【问题讨论】:

  • 我不清楚目标是什么 - 如果它只是将 JSON 的内容输出到控制台,那么为什么不直接使用 console.log(...)console.dir(...) 转储它呢? items 数组是干什么用的?
  • items 现已被删除 - 我希望能够动态创建表单,因此需要有名称、pre、文本字段和 textareas,然后是 post

标签: jquery json


【解决方案1】:

'Cleaner' 是一个非常主观的术语,但您可以通过使用箭头函数以及 Object.entries 来实现内部循环,使代码更简洁。

此外,您可以通过名称而不是括号符号来访问对象的属性。

最后你可以使用forEach() 代替jQuery 来循环。实际上根本不需要 jQuery。

let data = {sections:[{name:"Section 1",pre:"Pre text",post:"Post text",inputs:[{text_01:"Evidence 01",text_02:"Evidence 02",textarea_01:"Evidence 03",textarea_02:"Evidence 04"}]},{name:"Section 2",pre:"Pre text lad",post:"Post text bro",inputs:[{text_03:"Evidence 05",text_04:"Evidence 06",textarea_03:"Evidence 07",textarea_04:"Evidence 08"}]}]};

data.sections.forEach(section => {
  console.log('[+] Top Level');
  console.log(section.name);
  console.log(section.pre);
  console.log(section.post);
  
  section.inputs.forEach(input => {
    Object.entries(input).forEach(item => console.log(`${item[0]} - ${item[1]}`));
  });
});

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 2015-09-26
    • 2021-08-15
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多