Search code examples
arraysangularjsangularjs-ng-repeat

AngularJS ng-repeat and indexOf() to check objects


I have two json objects (data1 and data2) that have related information. Namely, both objects have properties (arrays) which in turn can have identical data. So, I am trying to figure out how to display those data with highlighting them properly, i.e. identical data with green color and non-identical with red color. Somehow it wrongly highlights all data with red color.

Here is the html:

<ul>
  <li ng-repeat="item in vm.data2.features"
      ng-class="vm.data1.features.indexOf(item) !== -1 ? 'check' : 'uncheck'">
    <span ng-bind="item.id"></span>
  </li>
</ul>

and objects:

vm.data1 = {
  id: '4569',
  name: 'Given data',
  features: [
    {id: "TEST_TEXT2", desc: 'smth12'},
    {id: "TEST_PPP", desc: 'smthsmthsmth'},
    {id: "TEST_ECASH", desc: "somelongtexthere"}
  ]
};

vm.data2 = {
  id: '1305',
  name: 'Base data',
  features: [
    {id: "TEST_BP", desc: 'smth'},
    {id: "TEST_TEXT2", desc: 'smth12'},
    {id: "TEST_PPP", desc: 'smthsmthsmth'},
    {id: "TEST_TEXT1", desc: 'blahblah'},
    {id: "TEST_ECASH", desc: "somelongtexthere"}
  ]
};

The full demo is here.

Any help would be appreciated.


Solution

  • Indexof() method will look for similarity in object references not the id itself. findIndex() method can help you here instead.

    vm.hasFeature = function(item){
    var hasElements= vm.data1.features.findIndex(function(e){
      return e.id == item.id;
    });
     console.log(item, hasElements);
     return hasElements;
    }
    

    And in html

    <li ng-repeat="item in vm.data2.features"
        ng-class="vm.hasFeature(item) > -1 ? 'check' : 'uncheck'">
    
    vm.hasFeature = function(item){
       var hasElements= vm.data1.features.findIndex(function(e){
          return e.id == item.id;
        });
        console.log(item, hasElements);
        return hasElements;
    } 
    

    CodePen Link: https://codepen.io/anon/pen/ewgLBN?editors=1010