如何根据id查找在数组中的位置

我有个数据,我像根据id完了获取到整个对象和他所在的位置,请问这个要如何获取啊

[
    {id:1,type:a}
    {id:2,type:b}
    {id:3,type:c}
    {id:4,type:d}
]
阅读 6.5k
8 个回答

楼上用法如下
image.png

var id = 3;
var arr = [
    {id:1,type:'a'},
    {id:2,type:'b'},
    {id:3,type:'c'},
    {id:4,type:'d'}
];
arr.find(item=>{
return item.id == id;
})
//{id: 3, type: 'c'}

借助原生方法 Array.findIndex 可以轻松做到:

function findById(list, id) {
  const index = list.findIndex(item => item.id === id)

  // 未找到时 index 为 -1,item 为 undefined
  return { index, item: list[index] }
}

const array = [
  { id: 1, type: 'a' },
  { id: 2, type: 'b' },
  { id: 3, type: 'c' },
  { id: 4, type: 'd' }
]

// index -> 1
// item -> { id: 2, type: 'b' }
const { index, item } = findById(array, 2)
var arr = [
    {id:1,type:'a'},
    {id:2,type:'b'},
    {id:3,type:'c'},
    {id:4,type:'d'},
]

function getIndexAndObjByID(id) {
  let res = {}; 
  for(let i = 0; i < arr.length - 1; i++) {
      if(arr[i].id === id) { 
          res = { location: i, obj: arr[i] }
          break
      }
  }
  return res
}

console.log(getIndexAndObjByID(2))
// output: { location: 1, obj: {id: 2, type: 'b'}}
新手上路,请多包涵

Array.findIndex(e => e.id == 1)

今天也遇到这个问题了

arr1 = [
    {id:1,type:'a'},
    {id:2,type:'b'},
    {id:3,type:'c'},
    {id:4,type:'d'}
]

arr1.find(res => res.id == 1)

//{id: 1, type: 'a'}
function find(arr, id) {
    for (var i = 0; i < arr.length; ++i) {
        if (arr[i].id === id) return [arr[i], i]; 
    }
    return [null, -1];
}
console.dir(find([
    { id: 1, type: "a" },
    { id: 2, type: "b" },
    { id: 3, type: "c" },
    { id: 4, type: "d" }
], 1)); // [{ id: 1, type: "a" }, 0]

这个题因为可以直接调用对象内置方法,所以最好直接调用最快。
因为你没有约定返回格式,我默认用数组来返回啦

function ArrFindByID(Arr,id){
  const index = Arr.findIndex(item => item.id === id)
  if (index<0) return [index,null];
  return [index,Arr[index]];
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题