简体   繁体   中英

JS comparing variables to multi level object

objects looking like this are coming my way:

var data = {
 a0: {
  name: 'long name 0',
  var1_min: '10',
  var1_max: '99',
  select: ['alpha', 'gamma'],
  display: 'value0'
 },
 b12: {
  name: 'long name 1',
  var1_min: '1',
  var1_max: '999',
  select: ['beta'],
  display: 'value1'
 },
 d7: {
  name: 'long name 2',
  var1_min: '1000',
  var1_max: '0',
  select: ['alpha', 'beta', 'gamma'],
  display: 'value2'
 }
}

I want to compare some variables to var1_min, var1_max, select and save name, display if one variable is between var1_min, var1_max and second variable is in select .

i have made this for testing:

<div style="text-align:center;" id="df">
 <div class="main">
  <form id="form" action="#">
   <fieldset>
    <label for="field1">field1
     <input type="text" name="field1" id="field1" />
    </label>
    <label for="field2">field2
     <select name="field2" id="field2">
      <option value="alpha">alpha</option>
      <option value="beta">beta</option>
      <option value="gamma">gamma</option>
     </select>
    </label>
   </fieldset>
   <br />
   <button type="submit">submit</button>
  </form>
  <span id="span"></span>
 </div>
</div>
$('#form').submit(function () {
 $('#span').empty();
 var field1 = $('#field1').val();
 var field2 = $('#field2').val();
 for (var x in data) {
  if (data.hasOwnProperty(x)) {
   $('#span').append(x + '<br />');
   for (var y in data[x]) {
    if (data[x].hasOwnProperty(y)) {
     $('#span').append(y + " => " + data[x][y] + '<br />');
    }
   }
  }
  if (field1 >= data[x].var1_min) {
   $('#span').append('true' + '<br />');
  }
 }
 return false;
});

if (field1 >= data[x].var1_min) always return true, even if the value in field1 is smaller.

http://jsfiddle.net/6UyPA/3/

Please lend me your eyeballs.

The object contains a string for var1_min , and val() returns a string too. To compare them as you expect, parse them as floats (or integers):

if (parseFloat(field1) >= parseFloat(data[x].var1_min));

See the updated jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM