[英]How to get an index of an element inside an object?
我正在尝试获取 object 中的元素索引,如下所示:
var array = [{spot_id: 6, spot_no: 6, gate_id: 6}, {spot_id: 16, spot_no: 17, gate_id: 5}, {spot_id: 5, spot_no: 5, gate_id: 5}, {spot_id: 11, spot_no: 11, gate_id: 5}, {spot_id: 15, spot_no: 16, gate_id: 4}, {spot_id: 4, spot_no: 4, gate_id: 4}, {spot_id: 10, spot_no: 10, gate_id: 4}, {spot_id: 14, spot_no: 15, gate_id: 3}, {spot_id: 9, spot_no: 9, gate_id: 3}, {spot_id: 3, spot_no: 3, gate_id: 3}, {spot_id: 8, spot_no: 8, gate_id: 2}, {spot_id: 13, spot_no: 14, gate_id: 2}, {spot_id: 2, spot_no: 2, gate_id: 2}, {spot_id: 7, spot_no: 7, gate_id: 1}, {spot_id: 12, spot_no: 13, gate_id: 22}]; var result = array.reduce( (acc, o) => (acc[o.gate_id] = (acc[o.gate_id] || 0)+1, acc), {} ); console.log(result) let index = result.findIndex(rank => rank === 4);
但它失败了。 我认为findIndex
仅适用于 arrays 而不是对象。
这是Fiddle中的这个例子:
预期 output:
例如,如果我想将其中一个元素的索引与一个数字进行比较,看看它是否为真(存在),例如:
for (var i = 0; i < 100; i++) { if (result[i] === 22) return true; //这里我正在检查值,但我想实际比较结果的索引而不是它的值。 }
findIndex 仅适用于 arrays 而不是对象,对。 你可以使用类似的东西:
let index= Object.keys(result).find(key=> result===4)
或者简单地说,
let index;
if(result[4])
index = 4
在我看来,您正在尝试查看gate_id === 22
有多少项目。 在这种情况下,您只需要:
result[22];
这是1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.