How to find a value in an array of objects in JavaScript?

前端 未结 10 2587
情话喂你
情话喂你 2020-11-28 18:08

I have an array of objects:

Object = {
   1 : { name : bob , dinner : pizza },
   2 : { name : john , dinner : sushi },
   3 : { name : larry, dinner : hummus         


        
10条回答
  •  爱一瞬间的悲伤
    2020-11-28 19:01

    If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:

    Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }
    

    You can now easily access it like this: Object['sushi']['name']

    Or if the object really is this simple (just 'name' in the object), you could just change it to:

    Obj = { 'pizza' : 'bob', 'sushi' : 'john' }
    

    And then access it like: Object['sushi'].

    It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.

提交回复
热议问题