使用Javascript / Jquery

时间:2016-12-22 12:19:19

标签: javascript jquery

我需要使用以下函数遍历数据数组,并在函数找到具有特定值的对象时返回“True”。但是,当我触发该函数时,它返回以下错误消息:

Cannot read property 'isTrue' of undefined

请你看看并解释我做错了什么?

var data = [
        {
           category: "1",
           values: [
               { key: "valueToGet1", isTrue:"true" },
               { key: "valueToGet2", isTrue:"false" }
           ]
        },
        {
           category: "2",
           values: [
               { key: "valueToGet3", isTrue:"false"},
               { key: "valueToGet4", isTrue:"true"}
           ]
        }
    ]

var getValue = function (value) {
    var result;
    $.each(data, function (i, item) {
        result = $.grep(item.values, function (e) {
            return e.key == value;
        })[0];
    })
    return result.isTrue == 'true';
}
    
console.log(getValue('valueToGet4')); //should return true;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2 个答案:

答案 0 :(得分:4)

您可以使用.some()

var getValue = function(value) {
  //Iterate each element in the array
  return data.some(d => {
    //iterate values property of the array item
    return d.values.some(v => {
      return v.key == value && v.isTrue == "true";
    })
  });
}

var data = [{
  category: "1",
  values: [{
    key: "valueToGet1",
    isTrue: "true"
  }, {
    key: "valueToGet2",
    isTrue: "false"
  }]
}, {
  category: "2",
  values: [{
    key: "valueToGet3",
    isTrue: "false"
  }, {
    key: "valueToGet4",
    isTrue: "true"
  }]
}]

var getValue = function(value) {
  return data.some(d => {
    return d.values.some(v => {
      return v.key == value && v.isTrue == "true"
    })
  });
}

console.log(getValue('valueToGet4')); //should return true;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

使用Reduce排除您不想要的项目:

var getValue = function (value) {
  var result = data.filter(function (item) {
    result = item.values.filter(function (e) {
        return e.key == value && e.isTrue == 'true';
    });
     return result.length > 0 
  })
  return result.length > 0 ;
}