YoroDiallo YoroDiallo - 2 months ago 9
AngularJS Question

how to check object name?

I have object and this object include objects too. It looks like:

$scope.data = {
tree : {
name : 'oak',
old : 54
},
dog : {
name : 'Lucky',
old : 3
},
system1 : {
name : '',
old : ''
},
baby : {
name : 'Jack',
old : 1
},
cat : {
name : 'Fluffy',
old : 2
},
system2 : {
name : '-',
old : '-'
}
}


As you can see this objects has obj name like - tree, dog, system etc. And I want to take only objects with name system, but this name can changes like system1, system123, system8. So I try to use this reg exp for ignore numbers

replace(/\d+/g, '')


But I can't reach this object name. I try this:

angular.forEach($scope.data, function(item){conole.log(item)}) // but it shows content in obj not obj name..


How can I reach this obj name and distinguish this 2 system objects?

Answer

Pass another param to the function like key to the forEach callBack Function. It is the key of the each object inside the object in your use-case.

Check the below example

var items = {
  car: {
    a: 123
  },
  dog: {
    b: 234
  },
  system: {
    c: 456
  }
};
angular.forEach(items, function(item, key) {
  console.log(key);
}); 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>