【问题标题】:find index of the object an array angularjs查找对象的索引数组angularjs
【发布时间】:2017-02-21 06:38:29
【问题描述】:

例如我有这个数组:

  $scope.records = [
    {
      "Name" : "Alfreds Futterkiste",
      "Country" : "Germany"
    },
    {
      "Name" : "Berglunds snabbköp",
      "Country" : "Sweden"
    },
    {
      "Name" : "Centro comercial Moctezuma",
      "Country" : "Mexico"
    },
    {
      "Name" : "Ernst Handel",
      "Country" : "Austria"
    }
  ];

如何从对象中获取值索引?以“国家”为例:“奥地利”这个指数是 3

【问题讨论】:

  • 这应该是一个简单的网络搜索

标签: javascript angularjs arrays


【解决方案1】:

您可以在最新的浏览器中使用Array.findIndex,但在 Internet Explorer 中不支持此功能,只有 Edge

let $scope = {};

$scope.records = [
    {
      "Name" : "Alfreds Futterkiste",
      "Country" : "Germany"
    },
    {
      "Name" : "Berglunds snabbköp",
      "Country" : "Sweden"
    },
    {
      "Name" : "Centro comercial Moctezuma",
      "Country" : "Mexico"
    },
    {
      "Name" : "Ernst Handel",
      "Country" : "Austria"
    }
];

let index = $scope.records.findIndex( record => record.Country === "Austria" );

console.log(index); // 3

对于 IE9 及更高版本的支持,您可以改用 Array.some

var $scope = {};

$scope.records = [{
  "Name": "Alfreds Futterkiste",
  "Country": "Germany"
}, {
  "Name": "Berglunds snabbköp",
  "Country": "Sweden"
}, {
  "Name": "Centro comercial Moctezuma",
  "Country": "Mexico"
}, {
  "Name": "Ernst Handel",
  "Country": "Austria"
}];

var index = -1;

$scope.records.some(function(obj, i) {
  return obj.Country === "Austria" ? index = i : false;
});

console.log(index);

【讨论】:

  • 您可以稍微修改一下以使用array.some。至少,一旦你找到索引,它就会停止迭代,同样的浏览器也支持。
  • @ste2425 - 我可以,我什至可以添加一个三元组
  • 在真实情况下您没有返回任何内容。这和return false 一样好,并且循环不会在第一次匹配时结束。我建议,obj.Country === 'Austria' && (index = i); return index != -1
  • @Rajesh - 它之所以有效,是因为如果它是0 以上的任何数字,则分配是真实的,如果它是0,那么它是第一个,并且可以返回 -> jsfiddle.net/adeneo/jgwu6v1j
  • 我不知道这个黑客。不错。
【解决方案2】:

使用 for - in 循环,因为它是一个 JSON 数组,你可以这样做

for(i in records) {
if(records[i].country=="Austria") 
console.log("index is :"+ parseInt(i)); // print index
}

【讨论】:

  • records 已经是一个 Javascript 对象。您不需要JSON.parsetypeof i 也是 string,而不是索引函数中预期的数字。
【解决方案3】:

我已经注册了这个方法,它就像魅力一样,

Array.prototype.getIndexByValue = function (name, value) {
        for (var i = 0, len=this.length; i <len; i++) {
            if (this[i][name]) {
                if (this[i][name] === value) {
                    return i
                }
            }
        }
        return -1;
    };

var d = [{
  "Name": "Alfreds Futterkiste",
  "Country": "Germany"
}, {
  "Name": "Berglunds snabbköp",
  "Country": "Sweden"
}, {
  "Name": "Centro comercial Moctezuma",
  "Country": "Mexico"
}, {
  "Name": "Ernst Handel",
  "Country": "Austria"
}];


var index = d.getIndexByValue('Country','Austria');
console.log(index)//will print 3

【讨论】:

  • 您正在将该变量 i 泄漏到窗口范围。此外,如果未找到该值,则返回 -1 而不是 null 以使其与 indexOf 函数保持一致。
【解决方案4】:

你可以这样做返回国家然后找到国家。

$scope.records.map((item) => { return item.Country;}).indexOf('Austria')

上面代码的问题是遍历每个元素一次生成映射,然后找到索引。您可以使用简单的 for 循环:

var index = (arr, k, v) => { 
   var i = -1;len = (arr || []).length;  
   for (i = 0; i < len; i++) { 
     if (arr[i][k] === v) 
       return i;
   }
   return -1;
} 

我注意到很多 findIndex 解决方案。请注意:FindIndex 方法已添加到 ECMAScript 6 规范中,根据 MDN,可能尚未在所有 JavaScript 实现中可用。

您可以将 polyfill 用于 findIndex(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) 并使用其他人建议的 findIndex 解决方案。如果您不想使用 polyfill,可以使用我提出的 map 和 indexOf 作为解决方案。

【讨论】:

    【解决方案5】:
    Use findIndex method - 
       var index = $scope.records.findIndex(x=>x.Country==='Austria')
    

    【讨论】:

      【解决方案6】:

      您可以为此使用array.findIndex

      var d = [{
        "Name": "Alfreds Futterkiste",
        "Country": "Germany"
      }, {
        "Name": "Berglunds snabbköp",
        "Country": "Sweden"
      }, {
        "Name": "Centro comercial Moctezuma",
        "Country": "Mexico"
      }, {
        "Name": "Ernst Handel",
        "Country": "Austria"
      }];
      var searchCountry = "Austria"
      var index = d.findIndex(x=>x.Country === searchCountry)
      console.log(index)

      注意:array.findIndex 是 ES6 的一部分。

      【讨论】:

        【解决方案7】:
        function getIndexByCountryName(country)
            var found = $scope.records.find(function(item){return item.Country === country});
            return $scope.records.indexOf(found);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-24
          相关资源
          最近更新 更多