javascript - 有效地查找数组中对象的索引

标签 javascript jquery json

我正在尝试查找数组中对象的索引。我知道有一种方法可以使用 underscore.js 执行此操作,但我正在尝试找到一种没有 underscore.js 的有效方法。这是我所拥有的:

var arrayOfObjs = [{
  "ob1": "test1"
}, {
  "ob2": "test1"
}, {
  "ob1": "test3"
}];

function FindIndex(key) {
  var rx = /\{.*?\}/;            // regex: finds string that starts with { and ends with }
  var arr = [];                  // creates new array
  var str = JSON.stringify(arrayOfObjs);          // turns array of objects into a string
  for (i = 0; i < arrayOfObjs.length; i++) {      // loops through array of objects
    arr.push(str.match(rx)[0]);                   // pushes matched string into new array
    str = str.replace(rx, '');                    // removes matched string from str
  }
  var Index = arr.indexOf(JSON.stringify(key));   // stringfy key and finds index of key in the new array
  alert(Index);
}

FindIndex({"ob2": "test1"});

JSFIDDLE

这可行,但恐怕效率不高。还有其他选择吗?

最佳答案

这是一种方法,使用 some() 并在对象不匹配时立即停止等,比较可靠且更有效。

var arrayOfObjs = [{
  "ob1": "test1"
}, {
  "ob2": "test1"
}, {
  "ob1": "test3"
}];

function FindIndex(key) {
    var index = -1;

    arrayOfObjs.some(function(item, i) {
    	var result = Object.keys(key).some(function(oKey) {
            return (oKey in item && item[oKey] === key[oKey]);
        });
        if (result) index = i;
        return result;
    });
    
    return index;
}

var index = FindIndex({"ob2": "test1"});

document.body.innerHTML = "'{\"ob2\": \"test1\"}' is at index : " + index;

关于javascript - 有效地查找数组中对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36946884/

相关文章:

javascript - 如何用js/jquery修改文本输入的值?

javascript - 如何创建一个将对象推送到数组中的函数,当再次推送时它将添加额外的对象

javascript - 如何获取自举开关的值

jquery - 使用 jQuery 跟踪 Flash 影片(对象/嵌入)上的点击

json - PlayFramework 配置 - 长字符串

ios - Json解析后取回数据

javascript - 将相同的文本添加到多个不同大小的 div

javascript - 如何以最佳性能接收未加载图像的错误事件

javascript - 隐藏滚动条但可以用鼠标滚动

php - 删除mysqli_connect()(HY000/2002)警告并通过JSON对象发送错误