0

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 ?

user2828442
  • 2,415
  • 7
  • 57
  • 105

4 Answers4

1

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);
bchampion
  • 191
  • 1
  • 11
  • It worked, trying to use the same technique but getting error, here is my code - https://pastebin.com/mf2rSDri , see line 46,47 , in console.log `this.array_no1` is showing this - https://www.dropbox.com/s/xj6qjf5tvp9dfy1/Screenshot%202017-05-29%2000.50.07.png?dl=0 , objects are shwing up in console but filter is not working, unable to get the `description` of the corresponding id – user2828442 May 28 '17 at 19:21
  • Try to replace === by == and let me kow. – bchampion May 28 '17 at 19:31
  • worked thanks but why `==` worked and `===` didnt ?? – user2828442 May 28 '17 at 19:39
  • Actually I think your id isn't a number but a string. So you compare a string with a number. The === return false but the == return true. You can have a look [here](https://stackoverflow.com/questions/523643/difference-between-and-in-javascript) for more informations about the equals operators. – bchampion May 28 '17 at 19:41
0

you can use es6 array syntax:

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

output:

Object {id: 2, name: "Tom"}
karser
  • 1,625
  • 2
  • 20
  • 24
0

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
Shivam
  • 3,462
  • 1
  • 15
  • 20
0

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))
Rick
  • 1,035
  • 10
  • 18