从数组值返回对象键

时间:2018-03-16 09:38:29

标签: javascript object

我想返回对象的键,其ContractID值等于10。因此,在此示例中,我想返回0

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

我已尝试使用filter方法,但它无法实现我想要的效果。

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

而是返回数组,而不是键。我该如何退还钥匙?

2 个答案:

答案 0 :(得分:2)

Object.keys()

上使用find



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




然而,你的"对象"看起来更像是应该是一个数组。可以将其直接创建为数组,也可以先将其转换为数组。然后使用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);




答案 1 :(得分:0)

您只需使用for in循环:



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