【问题标题】:javascript filter on an array, return the object and its position within the arrayjavascript过滤数组,返回对象及其在数组中的位置
【发布时间】:2021-02-11 14:14:32
【问题描述】:

我有一个这样的对象数组:

camera = [{ id, idCam, lat, lng }]

然后我有一个名为 idCamera 的 id,它对应于对象的 id。

我需要做的是,让我回到idCam 属性,然后让我回到数组中以下对象的位置。

我试过了,但它似乎不起作用,它返回对象但不返回密钥。

camera.filter((el, key) => {
 if (el.id === idCamera) return { idCam: el.idCam, key };
})

你能帮帮我吗?

【问题讨论】:

  • 过滤器不能那样工作。如果应包含该项目,则回调应返回 true,否则返回 false。任何为真的都包含在返回的数组中。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 为什么需要在特定项目之后选择项目?选择最后一项时会发生什么?
  • 为了确保我们以相同的方式使用术语,您的数组有一个带有四个属性的对象元素,对吧?当您说“键”时,您的意思是“索引”吗?数组有索引,以及这些索引处的元素。对象具有名称通常称为键的属性。

标签: javascript arrays object filter


【解决方案1】:

你可以使用'findIndex'函数:

const index = camera.findIndex(el => el.id === idCamera);
const foundedCamera = {index: index, idCam: camera[index].idCam}

【讨论】:

  • 简单实用的解决方案。 {index: index} 可以压缩为 {index}。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2017-10-07
    • 2019-11-02
    相关资源
    最近更新 更多