我从服务器端 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
这样的数字数组键只能在对象内部按升序数字顺序“排序”。如果您确实需要索引,您应该考虑更改后端以发送对象数组而不是单个对象。
关于javascript - 如何在对象中按键和值查找索引(但其完全对象没有数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60124750/