Check and get data from an array in JavaScript

  • A+
Category:Languages

I have an object:

var Obj1 = {id: 1, name: 'Apple'} 

And an array object:

var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice}, {'id: 2', 'name': 'Banana'}] 

How do I check Obj1.id in ArrObj? And I want the result to be: { id:1, name: 'Apple', 'eat':'rice'}

 


You can use Array.find():

var Obj1 = {id: 2, name: 'Banana'} var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice'}, {'id': 2, 'name': 'Banana'}]; var res = ArrObj.find(({id}) => id === Obj1.id ); console.log(res);

You can also use array destructuring way like:

var Obj1 = {id: 2, name: 'Banana'} var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice'}, {'id': 2, 'name': 'Banana'}]; var res = ArrObj.find(({id}) => id === Obj1.id); console.log(res);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: