1

Consider a model Company with both id and slug fields being unique. - A company slug will be used in its profile page, slug parsed to retrieve the company data from the state. - The company id is recorded as foreignkey in other models (let's say User), and the company data for a user will be fetched by its id.

Now, looking at my schema, I defined a Company entity as follow:

const options = {idAttribute: value => value.id};
const company = new schema.Entity("companies", undefined, options);

This is all find to query the company by id, but if I want to retrieve the current company when visiting https://example.com/company/company-slug/ , I then need to filter my hosts entities with lodash as follow

_.find(state.entities.companies, company => company.slug === "company-slug")

which isn't ideal.

What would be a better way to proceed ? Keeping a map of slug → id in the state ?

entities
    companies
       1: {slug: "a", ...}
       2: {slug: "b", ...}
       ...
    allIds: [1, 2, ...]
    slugsMap:
        a: 1
        b: 2

I would then be able to find my company in my selector as follow

const companies = state.entities.companies;
const companyId = companies.slugsMap["company-slug"];
const company = companies[companyId];

Looking forward to the brilliant solutions you can come up with!

EDIT: After reading Array vs. Object efficiency in JavaScript, I'm now a bit confused. Looks like array perform faster than objects, and we can use "associative arrays" (arrays with holes) to match array indexes to the objects ids.

Adrien Lemaire
  • 1,744
  • 2
  • 20
  • 29

0 Answers0