-3
let a=[{'id': '1234', 'name':'Server 1'}, {'id': '2262', 'name':'Server 2'}];

id='1234'

attachmentName: string;

I want to get the name, based on the specific ID.

Result: attachmentName= 'Server 1' based on id=1234

I tried a.filter, but it does not give me proper result. Any suggestions would be helpful

Sarah Mandana
  • 1,474
  • 17
  • 43

3 Answers3

2

What you looking for is find() method which return you an array item which match your condition.

let a = [{'id': '1234', 'name':'Server 1'}, {'id': '2262', 'name':'Server 2'}];
let yourWantedName = a.find(element => {
  return element.id === '1234';
}).name;
Alex - Tin Le
  • 1,982
  • 1
  • 6
  • 11
1

You actually want to use Array.find instead of Array.filter. Array.filter will return an array of matched results, whereas Array.find will return the first result found. Since you're trying to find something by id, you can do the following:

let a=[{'id': '1234', 'name':'Server 1'}, {'id': '2262', 'name':'Server 2'}];

id='1234'

const id1234 = a.find(o => o.id === id);
console.log(id1234);

Array.find

Array.filter

mwilson
  • 12,295
  • 7
  • 55
  • 95
0

really filter didn't work? hmmm. How about this. Have you tried using find method?

let a=[{'id': '1234', 'name':'Server 1'}, {'id': '2262', 'name':'Server 2'}];

const res = a.find( (item) => item.id === '1234' );

console.log(res)

Note: that find will return the first item that it will hit after that the loop goes out. you can find more about find method here

aRtoo
  • 1,686
  • 2
  • 18
  • 38