-1

Assume that i have this json obj:

var person=[{"name":"joe","age":21,"class":"a"},{"name":"moe","age":22,"class":"b"}];

i want to get the age of joe using given name which is joe. is there something like this: var age = person.name['joe'].age

Ali
  • 1,633
  • 7
  • 35
  • 58
  • You have an array, so you need to iterate the array and look for the object that has `name` of `joe`. –  Apr 24 '18 at 22:31
  • [This question](https://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-of-property) might be a better duplicate. The linked one (imo) is too broad and the solution to OP's question is not easily distilled from it's answers. – CRice Apr 24 '18 at 22:56
  • true, the answer is there, but i still believe that my question is much easier to read. thanks @Marcos Casagrande for your answer – Ali Apr 24 '18 at 23:00

1 Answers1

2

You can use Array.prototype.find to search for a specific property in an array of objects.

var person=[{"name":"joe","age":21,"class":"a"},{"name":"moe","age":22,"class":"b"}];
    
const joe = person.find(item => item.name === 'joe');

if(joe)
   console.log(`Joe is ${joe.age} years old`);
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98