如何通过文本搜索返回JSON数组中项目的索引位置?

How can I return an Index location for an item in a JSON array by searching with text?

本文关键字:项目 索引 位置 数组 文本 何通过 搜索 返回 JSON      更新时间:2023-09-26

这是我的JSON数组:

var planets = [{
  "Name": "Mercury",
  "Temperature": "427°C",
  "Position" : 1
}, {
  "Name": "Venus",
  "Temperature": "462°C",
  "Position" : 2
}, {
  "Name": "Earth",
  "Temperature": "16°C",
  "Position" : 3
}]

使用文本"地球"有一个方法,将返回我的项目地球在我的行星数组的索引位置?

例如:

planets.find("Earth")

Plain JS: findIndex

如果数组中有元素,则findIndex()方法返回数组中的索引该数组满足提供的测试功能。否则-1为返回。

[{
  "Name": "Mercury",
  "Temperature": "427°C",
  "Position" : 1
}, {
  "Name": "Venus",
  "Temperature": "462°C",
  "Position" : 2
}, {
  "Name": "Earth",
  "Temperature": "16°C",
  "Position" : 3
}].findIndex(x => x.Name === "Earth")

如果你在ie9 +中,你可以使用reduce函数

reduce()方法对累加器和每个累加器应用函数数组的值(从左到右)以将其减少为单个价值。

[{
  "Name": "Mercury",
  "Temperature": "427°C",
  "Position" : 1
}, {
  "Name": "Venus",
  "Temperature": "462°C",
  "Position" : 2
}, {
  "Name": "Earth",
  "Temperature": "16°C",
  "Position" : 3
}].reduce(function (foundSoFar, x, i) { // Note no arrow funcion
  if (foundSoFar < 0 && x.Name === "Earth") {
    return i;
  } else {
    return foundSoFar;
  }
}, -1);
或者,使用像ramda
这样的库的实现

试试这个:

var index = -1;
var val = 'Earth';
var filteredObj = planets.find(function(item, i){
  if(item.Name === val){
    index = i;
    return i;
  }
});
console.log(index, filteredObj);

与常规js:

function getIndexOfPlanet(name){
  for( var i in planets )
    if( planets[i].Name == name )
       return i;
}

使用Lodash实用程序方法查找索引,就像:

var planets = [{
  "Name"        : "Mercury",
  "Temperature" : "427°C",
  "Position"    : 1
}, {
  "Name"        : "Venus",
  "Temperature" : "462°C",
  "Position"    : 2
}, {
  "Name"        : "Earth",
  "Temperature" : "16°C",
  "Position"    : 3
}]
function getIndexOfPlanet(name){
  return _.findIndex(planets, { 'Name':name});
}
console.log( getIndexOfPlanet('Earth') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

var locationIndex;planets.forEach(函数(避署,印第安纳州){如果(避署。名称== "地球")locationIndex = ind;};console.log (locationIndex);

find或findIndex可能不支持某些浏览器,如IE.

您可以使用array#查找数组中当前正在处理的元素的index:

var planets = [{"Name": "Mercury","Temperature": "427°C","Position": 1}, {"Name": "Venus","Temperature": "462°C","Position": 2}, {"Name": "Earth","Temperature": "16°C","Position": 3}],
    earthIndex = -1,
    earth = planets.find(function(item, index) {
        if (item.Name === 'Earth') {
            earthIndex = index;
            return true;
        }
        return false;
    });
console.log('Earth index is:', earthIndex);