草庐IT

javascript - 如何创建可以处理条件的 JSON 对象?

coder 2024-07-23 原文

我想创建一个可以处理条件/分支的 JSON 对象。具体来说,我有如下工作流程:

对于第 1 步,用户有三个选择,根据他们做出的选择,他们会看到一组不同的第 2 步选择。相同的逻辑延伸到第 3 步,依此类推。

理想情况下,我希望所有这些数据都采用 JSON 格式,这样我就可以遍历它并根据用户的选择确定接下来需要向他们展示的选择。

有没有一种方法可以构建一个 JSON 对象(或者可能只是一个数组),让我可以这样做?

我应该提一下,我希望它足够灵活,这样如果我以后决定更改某个步骤的选择数量,那么我所要做的就是修改 JSON 对象/数组 (模型)而无需修改循环遍历对象/数组的逻辑。

非常感谢。

最佳答案

您正在构建的本质上是一个树数据结构。我建议从原始节点对象构建它,而不是包含对相同类型的子对象的递归引用。仅使用这一种类型的对象即可完全实现树,其中“最顶层”对象称为根对象,所有用户都从此处开始进行选择。从根开始,用户选择子节点,直到到达没有子节点的叶节点,即从那里不能进行进一步的选择。

所有节点都是这样的对象:

{
    "label": "Choice A",
    "question": "Choose subselection?",
    "children": [ (array of more objects of the same type) ]
}

其中 label 是您要为此选项提供的名称/标签,question 是用户必须回答的下一个问题以选择下一个子节点,而 children 是更多相同类型节点的数组,其中每个子节点的 label是该节点的 question 的一个可能答案。

为了举例说明,让我们假设下面的选择树,可以在一个假想的在线零售店中询问,它只销售两种主要类型的产品:服装和食品。在服装区,有不同颜色的牛仔裤、T 恤和连帽衫(为简单起见,假设我们已经知道顾客的尺码。)商店还出售少量类型的帽子。在食物区,有拉面、不同口味的苏打水和香蕉。在服装区,顾客可以在他们的黑色T恤上印上电视节目或摇滚乐队的标志,或者只买一件没有标志的纯黑色T恤。电视节目的标志可以额外印在蓝色连帽衫上,或者客户可以选择购买没有标志的蓝色连帽衫。

因此,面向客户的答案/问题对的决策树如下:

A: <start>
Q: What product category?
|
|--A: Clothes
|  Q: What type of clothing?
|  |    
|  |--A: Jeans
|  |  Q: Color of jeans?
|  |  |
|  |  |--A: Blue
|  |  |  Q: <end>
|  |  |
|  |  |--A: Black
|  |  |  Q: <end>
|  |  |
|  |  \--A: White
|  |     Q: <end>
|  | 
|  |--A: Shirt
|  |  Q: Type of shirt?
|  |  |
|  |  |--A: T-shirt
|  |  |  Q: Color of T-shirt?
|  |  |  |
|  |  |  |--A: Red
|  |  |  |  Q: <end>
|  |  |  |
|  |  |  |--A: Green
|  |  |  |  Q: <end>
|  |  |  |
|  |  |  |--A: Black
|  |  |  |  Q: Logo?
|  |  |  |  |
|  |  |  |  |--A: Rock band
|  |  |  |  |  Q: <end>
|  |  |  |  |
|  |  |  |  |--A: TV show
|  |  |  |  |  Q: <end>
|  |  |  |  |
|  |  |  |  \--A: No logo
|  |  |  |     Q: <end>
|  |  |  |
|  |  |  \--A: Orange
|  |  |     Q: <end>
|  |  |
|  |  \--A: Hoodie
|  |     Q: Color of hoodie?
|  |     |
|  |     |--A: Gray
|  |     |  Q: <end>
|  |     |
|  |     |--A: Blue
|  |     |  Q: Logo for hoodie?
|  |     |  |
|  |     |  |--A: TV show
|  |     |  |  Q: <end>
|  |     |  |
|  |     |  \--A: No logo
|  |     |     Q: <end>
|  |     |
|  |     |--A: Green
|  |     |  Q: <end>
|  |     |
|  |     |--A: Pink
|  |     |  Q: <end>
|  |     |
|  |     |--A: Brown
|  |     |  Q: <end>
|  |     |
|  |     |--A: Black
|  |     |  Q: <end>
|  |     |
|  |     \--A: Red
|  |        Q: <end>
|  |
|  \--A: Hat
|     Q: Type of hat?
|     |
|     |--A: Stetson
|     |  Q: <end>
|     |
|     \--A: Sombrero
|        Q: <end>
|
\--A: Food
   Q: Type of food?
   |
   |--A: Ramen noodles
   |  Q: <end>
   |
   |--A: Soda pop
   |  Q: Flavor
   |  |
   |  |--A: Cola
   |  |--Q: <end>
   |  |
   |  |--A: Lemon
   |  |--Q: <end>
   |  |
   |  |--A: Orange
   |  |--Q: <end>
   |  |
   |  |--A: Apple
   |  \--Q: <end>
   |
   \--A: Bananas
      Q: <end>

客户从“答案”<start> 开始,选择多项选择题,直到到达具有特殊“问题”<end> 的节点。

当我们将这棵树映射到 JSON 时,询问用户感兴趣的产品类别(衣服/食品)的根问题(上面的 <start>)可以具有标签值 null,因为它不是答案( child )任何其他问题。它是整个结构的第一个对象,所有其他节点都是它的子节点。无法进行进一步选择的叶节点(上面的 <end>)由 null 代替 question 字符串和 children 数组表示。所有其他节点指定一个标签字符串(节点“回答”的顶级问题)、下一个问题以及该问题的可能答案数组:

{
 "label": null,
 "question": "What product category?",
 "children": [
  {
   "label": "Clothes",
   "question": "What type of clothing?",
   "children": [
    {
     "label": "Jeans",
     "question": "Color of jeans?",
     "children": [
      {
       "label": "Blue",
       "question": null,
       "children": null
      },
      {
       "label": "Black",
       "question": null,
       "children": null
      },
      {
       "label": "White",
       "question": null,
       "children": null
      }
     ]
    },
    {
     "label": "Shirt",
     "question": "Type of shirt?",
     "children": [
      {
       "label": "T-Shirt",
       "question": "Color of T-shirt?",
       "children": [
        {
         "label": "Red",
         "question": null,
         "children": null
        },
        {
         "label": "Green",
         "question": null,
         "children": null
        },
        {
         "label": "Black",
         "question": "Logo?",
         "children": [
          {
           "label": "Rock band",
           "question": null,
           "children": null
          },
          {
           "label": "TV show",
           "question": null,
           "children": null
          },
          {
           "label": "No logo",
           "question": null,
           "children": null
          }
         ]
        },
        {
         "label": "Orange",
         "question": null,
         "children": null
        }
       ]
      },
      {
       "label": "Hoodie",
       "question": "Color of hoodie?",
       "children": [
        {
         "label": "Gray",
         "question": null,
         "children": null
        },
        {
         "label": "Blue",
         "question": null,
         "children": [
          {
           "label": "TV show",
           "question": null,
           "children": null
          },
          {
           "label": "No logo",
           "question": null,
           "children": null
          }
         ]
        },
        {
         "label": "Green",
         "question": null,
         "children": null
        },
        {
         "label": "Pink",
         "question": null,
         "children": null
        },
        {
         "label": "Brown",
         "question": null,
         "children": null
        },
        {
         "label": "Black",
         "question": null,
         "children": null
        },
        {
         "label": "Red",
         "question": null,
         "children": null
        }
       ]
      },
      {
       "label": "White",
       "question": null,
       "children": null
      }
     ]
    },
    {
     "label": "Hat",
     "question": "Type of hat?",
     "children": [
      {
       "label": "Stetson",
       "question": null,
       "children": null
      },
      {
       "label": "Sombrero",
       "question": null,
       "children": null
      }
     ]
    }
   ]
  },
  {
   "label": "Food",
   "question": "Type of food?",
   "children": [
    {
     "label": "Ramen noodles",
     "question": null,
     "children": null
    },
    {
     "label": "Soda pop",
     "question": null,
     "children": [
      {
       "label": "Cola",
       "question": null,
       "children": null
      },
      {
       "label": "Lemon",
       "question": null,
       "children": null
      },
      {
       "label": "Orange",
       "question": null,
       "children": null
      },
      {
       "label": "Apple",
       "question": null,
       "children": null
      }
     ]
    },
    {
     "label": "Bananas",
     "question": null,
     "children": null
    }
   ]
  }
 ]
}

以上是 100% 有效的 JSON:您可以将其复制并粘贴到 JSONtree 以逐级研究其结构。

故事的主旨是,这种可能相当复杂的可用用户选择和路径系统,可以在其核心(带叶子的节点)中用一个非常简单的数据结构来实现。复杂性源于您在节点之间定义的关系

关于javascript - 如何创建可以处理条件的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20052660/

有关javascript - 如何创建可以处理条件的 JSON 对象?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  5. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  6. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  7. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐