kittu
kittu

Reputation: 7008

Accessing object based on key provided

I have the following object and I want to access contact:[object] based on id: '77f97928d4e796d' which is the key. How do I do that?

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

Upvotes: 0

Views: 42

Answers (3)

Good Bye Blue sky
Good Bye Blue sky

Reputation: 196

You can use the Array.find method:

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

Upvotes: 1

Aravinder
Aravinder

Reputation: 503

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: '' 
}]

I am assuming you have multiple objects in array. You can just loop through the array and check for the 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;
    }
}

Now you will have contact object in myContact variable.

Upvotes: 1

Garfield
Garfield

Reputation: 2537

Iterate over your array of object & if the Id matches with the current object, get the contact object.

Upvotes: 0

Related Questions