我有一个像这样的对象数组:
camera = [{ id, idCam, lat, lng }]
然后我有一个名为idCamera的id,它对应于对象的id。
我需要做的是,让我回到一个idCam
属性,让我回到下面的对象在数组中的位置。
我试过这个,但它似乎不工作,它返回对象,但它不返回键。
camera.filter((el, key) => {
if (el.id === idCamera) return { idCam: el.idCam, key };
})
你能帮我一下吗?您可以使用' findinindex '函数:
const index = camera.findIndex(el => el.id === idCamera);
const foundedCamera = {index: index, idCam: camera[index].idCam}
方法Array.findIndex
将返回与给定条件匹配的数组中第一个元素的索引。
您可以使用此索引来构建您所查找的结果。
要小心处理数组中不包含所要查找的内容的情况。
const camera = [{
id: 0,
idCam: 42,
}, {
id: 1,
idCam: 69,
}];
const idCamera = 1;
function getCamValue(array, id) {
const index = camera.findIndex(x => x.id === idCamera);
if (index === -1) {
return -1;
}
return {
index,
idCam: camera[index].idCam,
};
}
console.log(getCamValue(camera, idCamera));