Getting an Element by id in JavaScript
You may need to get an array
element by its id. Let's see
how it's done.
Let the variable arr contain
an array of objects:
javascriptlet arr = [
{
id: 'GYi9GauC4gBF1e2SixDvu',
prop1: 'value11',
prop2: 'value12',
prop3: 'value13',
},
{
id: 'IWSpfBPSV3SXgRF87uO74',
prop1: 'value21',
prop2: 'value22',
prop3: 'value23',
},
{
id: 'JAmjRlfQT8rLTm5tG2m1L',
prop1: 'value31',
prop2: 'value32',
prop3: 'value33',
},
];
Let the element's id be stored in a variable:
javascriptlet id = 'IWSpfBPSV3SXgRF87uO74';
Let's get the element with this id.
Let's use the find method for this:
javascriptlet res = arr.find(elem => {
if (elem.id === id) {
return true;
} else {
return false;
}
});
The code can be shortened:
javascriptlet res = arr.find(elem => elem.id === id);