对象中的测试名称

时间:2016-12-08 18:13:45

标签: jquery json

this forum的帮助下,我构建了一个小脚本,用于测试json响应中对象中是否存在名称。如果该名称存在,那么我想从该对象中获取值并将其显示在div中的某个位置。

一切都很完美,但有一些product.specs名称几乎相同。在下面的示例中,我们有:

Height (mm)Height stacked (mm)

当json响应中存在上述两个时,它会自动抓取第二个Height(因此堆叠的高度(mm))。

使用下面的脚本时,会测试reHeight = /height/i;的名称。如何从该测试中排除Height stacked (mm)仅使用Height (mm)中的值?

所以我拥有的是这个

var data = {
  "product": {
    "specs": {
      "231638": {
        "id": 231638,
        "title": "Length (mm)",
        "value": "1200"
      },
      "231641": {
        "id": 231641,
        "title": "Width (mm)",
        "value": "800"
      },
      "231644": {
        "id": 231644,
        "title": "Height (mm)",
        "value": "144"
      },
     "239999": {
        "id": 239999,
        "title": "Height stacked (mm)",
        "value": "14400"
      } //etc etc
    }
  }
};

var length = 0, width = 0, height = 0,
  reLength = /length/i,
  reWidth = /width/i,
  reHeight = /height/i;

$.each(data.product.specs, function (specId, spec) {
  if (reLength.test(spec.title))
    length = spec.value;
  else if (reWidth.test(spec.title))
    width = spec.value;
  else if (reHeight.test(spec.title))
    height = spec.value;
});

var html = '<div class="somediv">' +
  '<span class="width">w: ' + width + '</span>' +
  '<span class="height">h: ' + height + '</span>' +
  '<span class="length">l: ' + length + '</span>' +
  '</div>';
$(document.body).html(html);

1 个答案:

答案 0 :(得分:1)

你可以使用正则表达式更具体:

reHeight = /height \(mm\)/i;

&#13;
&#13;
var data = {
  "product": {
    "specs": {
      "231638": {
        "id": 231638,
        "title": "Length (mm)",
        "value": "1200"
      },
      "231641": {
        "id": 231641,
        "title": "Width (mm)",
        "value": "800"
      },
      "231644": {
        "id": 231644,
        "title": "Height (mm)",
        "value": "144"
      },
     "239999": {
        "id": 239999,
        "title": "Height stacked (mm)",
        "value": "14400"
      } //etc etc
    }
  }
};

var length = 0, width = 0, height = 0,
  reLength = /length/i,
  reWidth = /width/i,
  reHeight = /height \(mm\)/i;

$.each(data.product.specs, function (specId, spec) {
  if (reLength.test(spec.title))
    length = spec.value;
  else if (reWidth.test(spec.title))
    width = spec.value;
  else if (reHeight.test(spec.title))
    height = spec.value;
});

var html = '<div class="somediv">' +
  '<span class="width">w: ' + width + '</span>' +
  '<span class="height">h: ' + height + '</span>' +
  '<span class="length">l: ' + length + '</span>' +
  '</div>';
$(document.body).html(html);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;