【问题标题】:Search Set Of Key Value Pairs in JSON在 JSON 中搜索键值对集
【发布时间】:2015-06-07 04:19:32
【问题描述】:

我有一个 JSON 对象中所有可能的唯一产品变体组合的列表 [这就是 woocommerce 构建它的方式]。例如,我有一个产品有 2 种尺寸 - size1 和 size2 和颜色 - color1 和 color2:

variant_list = [
       {
          "variation_id":328,
          "attributes":{
             "size":"size1",
             "color":"color1"
          }
       },
       {
          "variation_id":329,
          "attributes":{
             "size":"size2",
             "color":"color1"
          }
       },
       {
          "variation_id":330,
          "attributes":{
             "size":"size1",
             "color":"color2"
          }
       },
       {
          "variation_id":331,
          "attributes":{
             "size":"size2",
             "color":"color2"
          }
       ]

如果用户选择了特定的尺寸和颜色组合(使用单选按钮),例如选择了 size2 和 color1,我需要将变体 id: 329 传递给我的后端。使用属性标准集 = {"size":"size2","color":"color1"} 搜索我的 JSON 的最佳方法是什么。

我的 variant_list 对象已给出 - 我无法更改它,但可以根据需要构建我的条件对象以使此搜索简单高效。

我也尝试过并且有效,但我知道这是老派且效率低下:-( http://jsfiddle.net/v18h6qta/6/

【问题讨论】:

  • 等一下。我的 JSFiddle 恢复到旧版本。我现在就修。
  • 好的。更新了我的 JSFiddle。
  • 嗨 @user1880957 检查我的代码

标签: jquery json wordpress woocommerce


【解决方案1】:

您可以使用underscore js 库函数findfindWhere 或任何其他适合您查找该字段的方法。

例如

你可以使用类似的东西(我正在使用 javascript)

result = _U.findWhere(variant_list,{size:'user value',color:'user value'});
console.log(result.variation_id);

希望这会对你有所帮助。

【讨论】:

  • underscore.js 似乎是正确的选择。会检查的。
【解决方案2】:

我在你的小提琴中进行了简单的更新 我已添加此代码

function find(){
    var a=$("input[name=size]:checked").val();
    var b=$("input[name=color]:checked").val();

     for(var i=0;i< variant_list.length; i++){
         if(variant_list[i].attributes.size==a &&variant_list[i].attributes.color==b ){
           alert(variant_list[i].variation_id);   
         }
    }  

}

Click the demo

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 2012-10-30
    • 2018-01-05
    • 1970-01-01
    • 2023-02-24
    • 2015-07-10
    • 2017-08-31
    • 1970-01-01
    • 2015-01-20
    相关资源
    最近更新 更多