最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angularjs - How to find the index of an object in an array by checking property value in JavaScript? - Stack Overflow

programmeradmin6浏览0评论

I have an array like:

$scope.myArray = [{
  columnName: "processed1",
  dataType: "char"
}, {
  columnName: "processed2",
  dataType: "char"
}, {
  columnName: "processed3",
  dataType: "char"
}];

I want find the index of object which property value satisfy "processed2"

How can I do it? I tried using array.indexOf() method but I got response -1

I have an array like:

$scope.myArray = [{
  columnName: "processed1",
  dataType: "char"
}, {
  columnName: "processed2",
  dataType: "char"
}, {
  columnName: "processed3",
  dataType: "char"
}];

I want find the index of object which property value satisfy "processed2"

How can I do it? I tried using array.indexOf() method but I got response -1

Share Improve this question edited Aug 16, 2016 at 12:46 Rayon 36.6k5 gold badges53 silver badges78 bronze badges asked Aug 16, 2016 at 10:52 Soumya GangamwarSoumya Gangamwar 1,0224 gold badges20 silver badges46 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Use Array#findIndex, The findIndex() method returns an index in the array, if an element in the array satisfies the provided testing function. Otherwise -1 is returned.

Array#indexOf will fail as array contains objects, indexOf() tests the element using triple-equals operator and object is equals to object if it refers to same memory-location

var myArray = [{
  columnName: "processed1",
  dataType: "char"
}, {
  columnName: "processed2",
  dataType: "char"
}, {
  columnName: "processed3",
  dataType: "char"
}];
var index = myArray.findIndex(function(el) {
  return el.columnName == 'processed2';
});
console.log(index);

You can use a simple for loop.

for(var i=0;i < $scope.myArray.length; i++)
{
  if($scope.myArray[i].columnName == 'processed2') {
    // Do something with found item
    break;
  }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论