简体   繁体   中英

How to get a value of array of objects (pair key-value) in javascript?

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 n th 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).

The find() method which will return the value of the first element in the provided array that satisfies the provided testing function

 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'} ]; var res = sections.find(x => x.key === 12); console.log(res.label);

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM