![](/img/trans.png)
[英]Javascript How to find the index of an object, of an array of dictionaries, by a given key and value
[英]How can I find index by key and value in an object (but its completely object without an array)
我正在从服务器端 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,而不以某种方式转换它。
我认为(当然)我在这里遗漏了一个大概念,我无法通过谷歌搜索在网络上发现(实现)。
将对象转换为条目数组(条目是键值对,作为数组),然后您可以在该数组上使用.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
这样的数字数组键只能以数字升序在对象内部“排序”。 如果确实需要索引,则应考虑更改后端以发送对象数组而不是单个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.