2016-12-29 30 views
0

我有以下對象,我想根據id: '77f97928d4e796d'訪問contact:[object]這是關鍵。我怎麼做?根據提供的密鑰訪問對象

[ 
    { 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: '' 
    } 
] 
+1

如果您只有一個對象,是the'id'用途是什麼?這個對象又是如何存儲的? (你已經知道關鍵是'contact',那麼問題出在哪裏?) – UnholySheep

+0

看起來你是從控制檯複製的?你嘗試過'contact.id'嗎? – Mottie

+2

你是否要求從這樣的對象數組中發現? – Garfield

回答

0

遍歷你的對象&如果ID與當前對象匹配陣列,獲得接觸對象。

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變量中具有聯繫對象。

+0

Typo:'myObj'應該是'myContact'(在循環內的if中) – UnholySheep

+0

另外'arr [i] ''應該是'arr1 [i]'和'arr1 ++'應該是'i ++' – UnholySheep

+0

謝謝UnholySheep ..更正了錯字..... – Aravinder

1

可以使用Array.find方法:

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

相關問題