0

I need to loop through the data array using the following function and return 'True' in case the function finds an object with particular values. However, when I fire the function it returns the following error message:

Cannot read property 'isTrue' of undefined

Could you please take a look and explain what I am doing wrong?

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>
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
egurb
  • 1,176
  • 2
  • 14
  • 40
  • refer the link http://stackoverflow.com/questions/41197554/check-if-javascript-object-is-inside-an-existing-array/41197725?noredirect=1#comment69601072_41197725 – Amruth Dec 22 '16 at 12:20
  • The error said that `result` is undefined, so some problem you have with `data` object I guess. Did you try to pass the whole array as parameter? `getValue('valueToGet4', data)` and the definition: `var getValue = function(value, array)` – Marcos Pérez Gude Dec 22 '16 at 12:26

2 Answers2

4

You can use .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>
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Use Reduce to exclude the items you don't want:

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 ;
} 
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51