简体   繁体   中英

How to get element with key in list of dicts

I have a list of objects like this:

let colors = [
  {
    id: 0,
    color: "green",
  },
  {
    id: 1,
    color: "blue",
  },
  {
    id: 2,
    color: "orange",
  },
];

What is the best way (most optimized) to get an element with id=1 ... is there a way to do it without iterating through the list?

Small tip:

  • Use const instead of let when you're not reassigning values

Try doing the following:

                          // ✅ good pattern: destructuring. We only use what we need
const myColor = colors.find(({ id }) => id === 1)

You can iterate over the whole array once and create a lookup table if the array is static. Then, lookups can be done in constant time after O(n) preprocessing.

 let colors = [ { id: 0, color: "green", }, { id: 1, color: "blue", }, { id: 2, color: "orange", }, ]; const lookup = colors.reduce((acc,curr)=>(acc[curr.id] = curr, acc), {}); console.log(lookup[1]); console.log(lookup[2]);

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