如何创建嵌套的JSON数据类型?

时间:2016-01-11 22:17:18

标签: javascript html arrays json nested

我想创建以下数据的JSON文件,以便在使用JavaScript代码时创建下拉菜单。

用户首先选择该项目,这将限制尺寸选项。然后,他/她将使用大小,并根据选择价格确定。 选择所有必需元素后,将计算最终价格。

item   size             price ($)
 A      less than 3      5
 A      greater than 3   4
 B      less than 10     6
 B      between 10 & 20  5
 B      greater than 20  4

这是我到目前为止所写的内容:

items = [
    {
        "item" : "A",
        "size_1"  : "less than 3",
        "size_2"  : "greater than 3",
        "price_1"     : "5"
        "price_2"     : "4"
    },
    {
        "item" : "B",
        "size_1"  : "less than 10",
        "size_2"  : "between 10 & 20",
        "size_3"  : "greater than 20",
        "price_1"     : "6"
        "price_2"     : "5"
        "price_3"     : "4"
    }
]

这是我应该怎么做的吗?这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

您想要如何为数据建模,取决于您。你的方式很好,但让每个项目的数据模型看起来都是一样的好处。我可能会做以下事情:

var items = [
  {"item": "A", "size": "less than 3", "price": 5},
  {"item": "A", "size": "greater than 3", "price": 4},
  {"item": "B", "size": "less than 10", "price": 6},
  {"item": "B", "size": "between 10 & 20", "price": 5},
  {"item": "B", "size": "greater than 20", "price": 4},
];

如果您不需要将商品作为带有订单的列表,您可以将其设为item似乎是关键字的地图:

var items = {
  "A": [
    {"size": "less than 3", "price": 5},
    {"size": "greater than 3", "price": 4}
  ],
  "B": [
    {"size": "less than 10", "price": 6},
    {"size": "between 10 & 20", "price": 5},
    {"size": "greater than 20", "price": 4}
  ]
];

等。您可以想出很多方法来表示您的数据。只有你知道对你的实施最有意义的是什么。