我有个数据,我像根据id完了获取到整个对象和他所在的位置,请问这个要如何获取啊
[
{id:1,type:a}
{id:2,type:b}
{id:3,type:c}
{id:4,type:d}
]
我有个数据,我像根据id完了获取到整个对象和他所在的位置,请问这个要如何获取啊
[
{id:1,type:a}
{id:2,type:b}
{id:3,type:c}
{id:4,type:d}
]
楼上用法如下
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'}}
今天也遇到这个问题了
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]];
}
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
Array
的find
和findIndex
方法https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex