dev_jun
dev_jun

Reputation: 195

How to return a property of an object if its other property is known?

I have array of objects with unique names:

let arr = [
  {
    'name':'B',
    'id': 1
  },
  {
    'name': 'c',
    'id': 12
    },
  {
    'name': 'a',
    'id': 13
  }
]

How can I get id if I know the name. For example I have B and it need to return 1 ?

My solution :

const foo = (arr, name) => arr.filter(el => el.name === name)[0].id

foo(arr, 'B') // 1

Hope there is a better solution to this problem

Upvotes: 0

Views: 55

Answers (2)

Slai
Slai

Reputation: 22876

Array.prototype.find is fine for few lookups if you don't mind that it's not supported in IE, and that it can result in error if the item is not found. For multiple lookups, I recommend making a lookup object :

const arr = [ { name:'B', id: 1 }, { name: 'c', id: 12 }, { name: 'a', id: 13 } ]

const obj = arr.reduce((o, v) => (o[v.name] = v.id, o), {})

console.log( obj['B'] )   // 1
console.log( obj['A'] )   // undefined


If by any chance the data is from JSON.parse :

const obj = {}, json = '[{"name":"B","id":1},{"name":"c","id":12},{"name":"a","id":13}]'

JSON.parse(json, (k, v) => v.name ? (obj[v.name] = v.id) : v)

console.log( obj['B'] )   // 1
console.log( obj['A'] )   // undefined

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44087

You should use Array.prototype.find() instead of Array.prototype.filter(), because .find() returns only the first matching element of the array - .filter() returns all matching elements. Your code should look like this:

const foo = (arr, name) => arr.find(el => el.name == name).id;

Working snippet:

let arr = [
  {
    'name': 'B',
    'id': 1
  },
  {
    'name': 'c',
    'id': 12
  },
  {
    'name': 'a',
    'id': 13
  }
]

const foo = (arr, name) => arr.find(el => el.name == name).id;

var theID = foo(arr, 'B');

console.log(theID);

Upvotes: 1

Related Questions