如何根据此JSON中的其他已知属性返回正确的ID

时间:2014-01-28 08:30:55

标签: javascript jquery json

我是JSON的新手,如何根据variation_id从此JSON获取attributes_pa_trainer。 jQuery和/或vanilla js的答案都很受欢迎。

这是JSON。

[{
    "variation_id": "2446",
    "attributes": {
        "attribute_pa_trainer": "angus"
    },
    "image_src": "",
    "image_link": "",
    "image_title": "",
    "image_alt": "",
    "price_html": "",
    "availability_html": "",
    "sku": "TEST-ANGUS",
    "weight": " kg",
    "dimensions": "",
    "min_qty": 1,
    "max_qty": 0,
    "backorders_allowed": false,
    "is_in_stock": true,
    "is_downloadable": false,
    "is_virtual": true,
    "is_sold_individually": "no"
}, {
    "variation_id": "2447",
    "attributes": {
        "attribute_pa_trainer": "anthony"
    },
    "image_src": "",
    "image_link": "",
    "image_title": "",
    "image_alt": "",
    "price_html": "",
    "availability_html": "",
    "sku": "TEST-ANTHONY",
    "weight": " kg",
    "dimensions": "",
    "min_qty": 1,
    "max_qty": 0,
    "backorders_allowed": false,
    "is_in_stock": true,
    "is_downloadable": false,
    "is_virtual": true,
    "is_sold_individually": "no"
}]

我正在寻找完成以下功能的解决方案

// On button click
$('.purchase_btn').click(function() {
    // Set trainer to the value of the button's data attribute
    var trainer = $(this).data('trainer');
    // variations_json is the full json
    var variations_json = $('.variations_form').data('product_variations');
    // Get the variation id based on the trainer
    var variation_id = [some way of getting the variation ID from the above json];
    // Set a hidden field to the variation id
    $('#variation_id').val(variation_id);
});

提前致谢。

3 个答案:

答案 0 :(得分:2)

使用grep method过滤对象。假设您找到一个,结果是一个包含一个项目的数组,因此您可以从该项目中获取变体ID:

var variation_id = $.grep(variations_json, function(o){
  return o.attributes.attribute_pa_trainer == trainer;
})[0].variation_id;

答案 1 :(得分:0)

so [{id:1,name:“test”},{id:2,name:“test2”}]是一个json对象数组。所以,我对你的问题有点困惑,你是否试图从数组中的每个json对象获取variation_id?或者你想循环遍历数组并找到一个json对象并获取其variation_id?

Guffa的解决方案可行,但你只需要小心jquery函数,如果没有找到,那么它将返回一个空数组,所以如果数组为空,array [0]将返回错误。

答案 2 :(得分:0)

另一种方法可能是使用jQuery的每个函数循环访问JSON。我认为grep内部或多或少都相同。这看起来有点像这样:

$.each(variations_json, function() {
    if(this.attributes.attribute_pa_trainer == trainer){
    variation_id =this.variation_id;
}
});

缺点是,无论如何都会遍历整个JSON,即当找到训练师时,它显然不会中断。

相关问题