ditto
ditto

Reputation: 6277

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?

Upvotes: 0

Views: 53

Answers (2)

Zenoo
Zenoo

Reputation: 12880

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

Upvotes: 0

baao
baao

Reputation: 73241

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

Upvotes: 2

Related Questions