简体   繁体   中英

How to get an index of an element inside an object?

I am trying to get the index of an element inside an object like below:

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

but it fails. I think findIndex is only for arrays and not objects.

Here is this example in Fiddle :

Expected output:

For example if I want to compare the index of one of the elements with a number and see if its true (exists) like:

for (var i = 0; i < 100; i++) { if (result[i] === 22) return true; //here I am checking the value but I want to actually compare the index of result not its value. }

findIndex is only for arrays and not objects, right. You can use something like:

let index= Object.keys(result).find(key=> result===4)

or simply,

let index;
if(result[4])
    index = 4

Looks to me that you're trying to see how many items are there with gate_id === 22 . In that case all you need is:

result[22]; 

which is 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM