首页 > 解决方案 > 如何在对象中按键和值查找索引(但它的完全对象没有数组)

问题描述

我从服务器端 laravel 返回以下数据。

  response = {
    "1": {
      "id": 1,
      "title": "Port1",
      "code": "P",
      "accounting_code": "119"
    },
    "2": {
      "id": 2,
      "title": "Port2",
      "code": "P2",
      "accounting_code": "120"
    },
    "4": {
      "id": 4,
      "title": "Port3",
      "code": "P3",
      "accounting_code": "122"
    },
    "5": {
      "id": 5,
      "title": "Port4",
      "code": "P4",
      "accounting_code": "123"
    }
  }

即使将集合变成数组(toArray()),这里的响应也不会改变。所以我必须处理这个,但是当我使用这个代码时:

response.findIndex( p => p.code == 'P1') // or .find() or .indexOf()

我得到一个findIndex is not a function错误。我知道它必须是一个对象数组才能使用该函数,但必须有一种简单的方法来轻松地动态处理这个 laravel 响应。我的意思是使用内置的 laravel 响应,而不以某种方式对其进行转换。

我认为(当然)我在这里遗漏了一个大概念,我无法通过谷歌搜索在网络上发现(实现)。

标签: javascriptlaravel

解决方案


将对象变成一个条目数组(一个条目是一个键值对,作为一个数组),然后你就可以.find在那个数组上使用了。如果条目与条件匹配,您可以从中提取键(或值或索引):

const response = {
  "1": {
    "id": 1,
    "title": "Port1",
    "code": "P",
    "accounting_code": "119"
  },
  "2": {
    "id": 2,
    "title": "Port2",
    "code": "P2",
    "accounting_code": "120"
  },
  "4": {
    "id": 4,
    "title": "Port3",
    "code": "P3",
    "accounting_code": "122"
  },
  "5": {
    "id": 5,
    "title": "Port4",
    "code": "P4",
    "accounting_code": "123"
  }
};
const entry = Object.entries(response).find(([, obj]) => obj.code === 'P3');
if (entry) {
  console.log(entry[0]);
}

如果你不关心匹配的键或值,只关心索引,然后Object.values获取一个数组并调用findIndex它:

const response = {
  "1": {
    "id": 1,
    "title": "Port1",
    "code": "P",
    "accounting_code": "119"
  },
  "2": {
    "id": 2,
    "title": "Port2",
    "code": "P2",
    "accounting_code": "120"
  },
  "4": {
    "id": 4,
    "title": "Port3",
    "code": "P3",
    "accounting_code": "122"
  },
  "5": {
    "id": 5,
    "title": "Port4",
    "code": "P4",
    "accounting_code": "123"
  }
};
const index = Object.values(response).findIndex(obj => obj.code === 'P3');
console.log(index);

但是代码通常不应该依赖于具有特定顺序的对象的键。虽然顺序是确定性的,但它可能会有些混乱,并且数字数组键1只能5在对象内部按数字升序“排序”。如果您确实需要索引,则应考虑更改后端以发送对象数组而不是单个对象。


推荐阅读