0

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?

3
  • const keys = Object.keys(objname).filter(key => objname[key].ContractId === 10) Commented Mar 16, 2018 at 9:40
  • I'm puzzled by it being an object instead of an array Commented Mar 16, 2018 at 9:41
  • this filter yeah returns a keys which is an array but with unique item. => get your item with index 0 Commented Mar 16, 2018 at 9:42

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.