根据提供的密钥访问对象

时间:2016-12-29 11:24:21

标签: javascript

我有以下对象,并且我希望基于contact:[object]来访问id: '77f97928d4e796d',这是关键。我怎么做?

[
    { contact: [Object],
          id: '77f97928d4e796d',
          createdDate: Thu Dec 29 2016 16:58:13 GMT+0530 (IST),
          name: 'Test',
          profileData: '' 
    },
    { contact: [Object],
        id: '77f97928d4e7944',
        createdDate: Thu Dec 29 2016 17:04:13 GMT+0530 (IST),
        name: 'Test2',
        profileData: '' 
    }
] 

3 个答案:

答案 0 :(得分:1)

var arr1 = [{ contact: [Object],
    id: '77f97928d4e796d',
    createdDate: Thu Dec 29 2016 16:37:21 GMT+0530 (IST),
    name: 'Test',
    profileData: '' 
}, { contact: [Object],
    id: '888fghwtw678299s',
    createdDate: Thu Dec 29 2016 16:37:21 GMT+0530 (IST),
    name: 'Test',
    profileData: '' 
}]

我假设你在数组中有多个对象。你可以循环遍历数组并检查id。

var providedKey = '77f97928d4e796d';
var myContact = null;
for(var i=0; i<arr1.length; i++){
    if(arr1[i].id == providedKey){
        myContact = arr1[i].contact;
        break;
    }
}

现在,您将在myContact变量中拥有联系对象。

答案 1 :(得分:1)

您可以使用Array.find方法:

&#13;
&#13;
var array = [{ contact: [Object],
id: '77f97928d4e796d',
createdDate: 'Thu Dec 29 2016 16:58:13 GMT+0530 (IST)',
name: 'Test',
profileData: '' 
},
{ contact: [Object],
id: '77f97928d4e7944',
createdDate: 'Thu Dec 29 2016 17:04:13 GMT+0530 (IST)',
name: 'Test2',
profileData: '' 
}];

//Change the id string for the id you looking for
console.log(array.find(obj => obj.id == '77f97928d4e7944'));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

迭代你的对象数组&amp;如果Id与当前对象匹配,则获取联系对象。