如何通过搜索文本来返回JSON数组中某项的索引位置? [英] How can I return an Index location for an item in a JSON array by searching with text?

查看:111
本文介绍了如何通过搜索文本来返回JSON数组中某项的索引位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JSON数组:

Here is my JSON array:

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

}, {
  "Name": "Earth",
  "Temperature": "16°C",
  "Position" : 3
}]

使用文本"Earth"是否可以向我返回我的Planets数组中"Earth"项的索引位置?

Using the text "Earth" is there a method that would return me the index location of the item Earth in my Planets array?

例如:

planets.find("Earth")

推荐答案

尝试一下:

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);

这篇关于如何通过搜索文本来返回JSON数组中某项的索引位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆