Zeyukan Ich'
Zeyukan Ich'

Reputation: 693

Avoid sort order JavaScript of objects

what workaround could be possible to access objects by index and keeping the order ?

values: {
        134: {id: 134, name: "A"},
        120: {id: 120, name: "B"},
        1722: {id: 1722, name: "C"},
    }

I have objects of objects that I access by key to avoid unnecessary loop, the fact is that doesn't keep order at all because JavaScript re-sort them!

It will swap 134 and 120 to match an ascending sort order. Since Javascript can't handle associative array key => value, how can I do such things and avoid loops to access my objects?

Thanks you for any advice!

Upvotes: 1

Views: 63

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370659

You can use a Map instead, which preserves insertion order for keys:

const values = new Map();
values.set(134, {id: 134, name: "A"});
values.set(120, {id: 120, name: "A"});
values.set(1722, {id: 1722, name: "A"});

for (const value of values.values()) {
  console.log(value);
}

// or
console.log(values.get(134));

Upvotes: 3

AKX
AKX

Reputation: 168843

Keep an array of the desired order in addition to the map of items:

const itemMap = {
  134: { id: 134, name: "A" },
  120: { id: 120, name: "B" },
  1722: { id: 1722, name: "C" },
};
const itemOrder = [120, 134, 1722];

itemOrder.forEach(id => {  // iterate in order
  console.log(itemMap[id]);
});

console.log(itemMap[1722]); // access randomly

Upvotes: 1

Related Questions