简体   繁体   中英

Return object key from array value

I want to return the key of the object where it's ContractID value equals 10 . So in this example I want to return 0 .

{
    0 : {ContractID: 10, Name: "dog"}
    1 : {ContractID: 20, Name: "bar"}
    2 : {ContractID: 30, Name: "foo"}
}

I've tried using the filter method but it doesn't work how I'd have wanted.

var id = objname.filter(p => p.ContractID == 10); 

This instead returns the array, not the key. How can I return the key?

Use find on the Object.keys()

 let obj = { '0' : {ContractID: 10, Name: "dog"}, '1' : {ContractID: 20, Name: "bar"}, '2' : {ContractID: 30, Name: "foo"} } let res = Object.keys(obj).find(e => obj[e].ContractID === 10); console.log(res); 

However, your "object" looks more like it should be an array. Either create it directly correct as an array, or convert it to one first. Then use findIndex()

 let obj = { '0' : {ContractID: 10, Name: "dog"}, '1' : {ContractID: 20, Name: "bar"}, '2' : {ContractID: 30, Name: "foo"} }; obj.length = Object.keys(obj).length; let arr = Array.from(obj); let key = arr.findIndex(e => e.ContractID === 10); console.log(key); 

You could simply use a for in loop :

 var o = { 0 : {ContractID: 10, Name: "dog"}, 1 : {ContractID: 20, Name: "bar"}, 2 : {ContractID: 30, Name: "foo"} }; var k; for(key in o){ if(o[key].ContractID == 10){ k = key; break; } } console.log(k); 

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