简体   繁体   中英

Is there an efficient way to access an object in an array with its key?

data = [
    {
       _id: 1234,
       name: 'ddd'
    },
]

Let's say I have this Object array in JavaScript and I want to retrieve the object based on the _id.

I know I can just do filter like,

data.filter((item, key) => { return item._id === "1234" })

But I wonder if there is a faster way of doing this, maybe like retrieving as I am accessing a dictionary with a key O(1) .

Any help?

You can use Array.prototype.find() :

data.find(({ _id }) => _id === '1234')
// or without destructuring and implicit return
data.find(item => { return item._id === '1234' })

If you want O(1) lookups, I'd suggest converting to a Map

const mappedData = new Map(data.map(item => ([item._id, item])))

or via Array.prototype.reduce()

const mappedData = data.reduce((map, item) => map.set(item._id, item), new Map())

Note that this operation is at best O(n) but it only needs to happen once.

Now you can fetch items with O(1) time complexity

const item1234 = mappedData.get(1234)

No. If you want to access them in constant time complexity O(1) then use that property as the index or key.

Here, the indices are 0,1,2 etc. So you can get data[0] , data[1] without searching.

But if you want to find something inside the value at that index, then you have to search and it is not a constant time complexity operation.

If you need to do this query more than one time, by converting the array to a lookup object will take o(n) at first time, but the later query will only take constant time complexity o(1)

const dataWithIdKey = data.reduce((acc, item) => {
   acc[item._id] = item;
   return acc;
}, {});


const item1234 = dataWithIdKey['1234']

on the other hand, if there is only one time query. the find function will stop to run when it found the item with desired key. or a for loop can also solve this problem as well. however, the worse case of both still take o(n)

data.find( ({_id}) => _id === '1234' );
for(let i = 0; i < data.length; i++){
  if(data[i]._id === '1234'){
      // do something here
      break;
  }
}    

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