1

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!

1
  • 1
    you mean access like values[134] ? Commented May 8, 2020 at 10:58

2 Answers 2

3

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));

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.