0

I have an array of objects like below:

const arrObj = [
    {
        id: '1',
        name: 'n1',
        type: 'type1',
    },
    {
        id: '2',
        name: 'n2',
        type: 'type1',
    },
    {
        id: '3',
        name: 'n3',
        type: 'type2',
    }, 
    {
        id: '4',
        name: 'n4',
        type: 'type2',
    } 
]
         

Now I have a variable like arrId = 1. I want to filter the arrObj with the arrId and return its name.

So for arrId '1', I want to retrieve 'n1'.

How can I do this? Could someone help me with this using react, es6 and javascript? Thanks.

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
stackuser
  • 199
  • 1
  • 13
  • `arrObj.find(obj => obj.id === arrId).name`. Note that `find` will return undefined if it can't find an object matching the predicate, so you'll have to handle that. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find – Andrew Li Jan 31 '21 at 21:21
  • See: https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes – Ed Lucas Jan 31 '21 at 21:21
  • Not a great duplicate... this deals with matching just one property and the duplicate is bit asker-specific. – Andrew Li Jan 31 '21 at 21:25
  • @AndrewLi How to filter array of objects by an object property seems duplicate enough to me. Granted, it seems what the OP wants is different than what they ask for and a bit ambiguous, but based on title and description I feel it's a duplicate as the linked question answers exactly how to do this. If you or OP disagree the question can always be edited/updated to explain why/how it is different and vote to reopen. – Drew Reese Jan 31 '21 at 21:33

0 Answers0