egurb
egurb

Reputation: 1216

Find object in array using Javascript/Jquery

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>

Upvotes: 0

Views: 71

Answers (2)

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

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 ;
} 

Upvotes: 1

Satpal
Satpal

Reputation: 133403

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>

Upvotes: 4

Related Questions