user2828442
user2828442

Reputation: 2515

How to fetch "name" property from an array if i know its corresponding "id"

I have a simple array with id and name. If i know the id then how can i fetch the name, array is shown below:

var dataobj = [
  {id:1,name:"Jessica"},
{id:2,name:"Tom"},
{id:3,name:"Will"}
];

i have the id for example 2 with me in a variable, how can i get the name which belongs to this id ?

I have clickedID=2 value in my slist.component.ts and i want to fetch its corresponding name, how can i do it ?

Upvotes: 0

Views: 438

Answers (4)

Rick
Rick

Reputation: 1055

You can do something more readable and reusable with a dynamic find

var dataobj = [
{id:1,name:"Jessica"},
{id:2,name:"Tom"},
{id:3,name:"Will"}
];

let getNameFromObjId = obj => id  => obj.find(x=> x.id===id).name; 
console.log(getNameFromObjId(dataobj)(2))

Upvotes: 0

bchampion
bchampion

Reputation: 201

To log the name which belongs to the id 2, it's as simple as following :

 let obj = dataobj.find(obj => obj.id === 2);
 console.log(obj.name);

Upvotes: 1

Shivam
Shivam

Reputation: 3622

You can use the array find method

    const secondItem = dataObj.find(function (item){
     return item.id === 2;
})

Then name can be accessed as

secondItem.name

Upvotes: 0

karser
karser

Reputation: 1693

you can use es6 array syntax:

dataobj.find(el => el.id === 2)

output:

Object {id: 2, name: "Tom"}

Upvotes: 0

Related Questions