Good time, i have an array of objects like this:
var sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
So, for example, i want to get label that is for key=12 (it have to be Dolores Black). If i use something like:
alert(sections[11]['label']);
this will be wrong, cause it will find 12th element of array, not an element with key=12. So what is th right expression for my case? Thanks
Use Array#find:
let sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
let res = sections.find(({key}) => key === 12)?.label;
console.log(res);
If you know that the element is nth in the array, use sections[n - 1]['label']; for example, to get Dolores Black (the 3rd element), you'd do:
sections[2]['label']; // 3 - 1 = 2
If you don't know the position of the element beforehand, you have to give some condition to JavaScript, so that it can find it; in your case, the condition is item.key === 12:
sections.find((item) => item.key === 12)['label'];
Note that in both cases we assume that the element actually exists in the array (if it doesn't, there will be errors).
I would wrap this in a function. Inside function i use the js function find(). If you have more items with the same id then i would use filter instead find.
const sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
const id = 11;
function getLabel(id) {
return sections.find(e => e.key === id)['label'];
}
console.log(getLabel(id))