Search code examples
javascriptarraysobjecttraversal

Best practice for accessing information within an array of objects. [.find() vs. .filter() vs. creating a reference object]


Does anybody know if it's more efficient to create a new helper object or use locator methods [like .find() or .filter()] to help translate some unique identifiers in a set of data to the names they represent?

I'm working with an array of objects to make a table; each object holds the information to display on one row of the table.

example:

    // Data:
    [ { id: someCardIdxx,
        name: "card1",
        pos: 1,
        customFields: 
          [{ id: "1234",
             value: 32 },
          {  id: "4321",
             idValue: "876"}],
      },
      { //...x50 
      }
    ]  

To get information about the customFields, I need to refer to an kind of definition object that applies to the entire list. It has data for understanding how to translate the custom field id's and idValue's.

example:

// Custom Field Definitions:
[ { id: "1234",
    type: "number",
    display: true,
    name: "Size",
  },
  { id: "4321",
    type: "list",
    display: true,
    name: "Color",
    options: 
       [{ id: "987",
          name: "Yellow"},
        { id: "876", 
          name: "Green"}]
   },
   { // ...x8
   }
]

When analyzing each of the card objects in the Data array, I can use the Definitions array with the help of .find() or .filter(), but that means searching for an object within the Definitions array each time I want to interpret a card.

Would it be better for optimization if I took the Definitions array of customField objects and converted it into a single organized object that I could reference?

The end goal could be something like this, with the field ids used as property keys:

// New Definitions Object: 
{ "1234": "Size",
  "4321": {
    "name": "Color",
    "options": {
      "987": "Yellow",
      "876": "Green"
    }
  },
  // ...x8
}

Is it faster to access this information as properties after creating an object or by finding it in the array with the appropriate id? Which of these strategies (or other) would typically be best to use?


Solution

  • I am not sure is it about best practices or just my experience. From my point of view you should not build your application data model looking to data provider (backend) responses structure, but looking to your functionality.

    According to my experience you should keep collection of items in array only if items order is important. If each item has unique identifier and order does not meter the best option is regular Map (or id to value object)

    But any way, for 50 items you can do it in any way, the difference will be invisible