1

How to find an item that matches a field using javascript?

i have an array of object like below,

const items = [
    {
        id: '1',
        category: 'one',
    },
    {
        id: '2',
        category: 'two',
    }
]

from the above items array of objects i want to get the id of that object whose category is equal to 'two'

so the output should be 2.

so i have tried something like below,

const id = items.map(item => {
    return item.find(i => i.category === '2');
}

but this throws an error cannot read item of undefined.

could someone help me fix this. i am new to programming. thanks.

Submitted July 02nd 2021 by Admin

Answers
0

item.find() will work for arrays. Yours is an object. Also, .category === '2' will not work, so that is a typo.

You can use a filter() here :

let ans = items.filter((x)=>{ return x.id === '2'
});

Note: this will return an array of matching objects. If you are absolutely sure there will be one element matching this you can do this:

let ans = items.filter((x)=>{ return x.id === '2'
})[0]; 

Admin | 2 months ago


0

const id = items.map(item => { return item.find(i => i.category === '2');
}

find can be used on arrays not on objects. In the above code item is an object.

const item = items.find((item) => item.id === '2')

This would give you the whole object with id = 2.

Admin | 2 months ago


0

you can use the reduce method as well

const id = items.reduce((acc, item,index) => { if(item.category === 'two') { return item.id; } })

Admin | 2 months ago


0

const items = [ { id: '1', category: 'one', }, { id: '2', category: 'two', }
]
const objectWithCategoryEquals2 = items.find(item => item.category === 'two')
const id = objectWithCategoryEquals2.id

Find returns an item in an array that matches your predicate, to get the id you then have to do .id on the returned object.

Your code snippet below doesn't work because you're checking i.category to be equal '2', where the data says its 'two' instead, so the item is not found and undefined is returned.

const id = items.map(item => { return item.find(i => i.category === '2');
}

Admin | 2 months ago



Relevant Questions




Deleting a todo - MERN Stack

September 10th 2021