2016-12-29 53 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'));