Meules Meules - 1 month ago 8
jQuery Question

Select on name in object

First of all I'm still learning so please be gentle :)
I have a json response where I want to select some specific elements.
I'm trying to get some elements with a specific name inside an object and want to test if it matches a predefined name. These are product specifications with a specific name like "length", "width" etc.

I'm having trouble to find those specific names and if they are found get their "value" attribute.

So what I have is this:

JSON response:

{

"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"
} //etc etc


Now I want to grab only the two
value
attributes from specifications "length" and "height". So first I have to look if those two names are present and matches "length" and "height" and if so grab their
value
attributes. That's where I need some help.

The end result must be

<div class="somediv">
<span class="width">1200</span>
<span class="height">144</span>
</div>


So what I have is this:

$.getJSON(url', function(data){
var specsHtml = [];

$.each(data.product.specs, function(index, spec){
// in here I need to test if the name of the spec equals "length or Height".
specsHtml.push(spec.value);
});
specsHtml = specsHtml.join('');
}
container.find('.product-bottom .measurements span').html(specsHtml);
});


I'm completly stuck in here. I have tried things like:

(spec.hasOwnProperty("title"));


or

var specs = [];
data.product.specs.forEach(data.product.specs => {
if (data.product.specs)
for (var spec in data.product.specs)
specs.push(spec);
})


Any help greatly appreciated :)

Answer

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"
      } //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);
.somediv > span { padding: 10px;  display:inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments