0
const a = {};
array.forEach(item => {
  a[item.id] = item;
})

when i get a, I found it was sort by item.id. How to prevent the sort when forEach. if array = [{id: 2}, {id: 6}, {id : 1}], and then I get a = {1: {id: 1}, 2: {id: 2}, 6: {id: 6}}. my want is a={2: {id: 2}, 6: {id:6}, 1: {id: 1}}

Jiayu Yang
  • 101
  • 1
  • 1
  • 5

1 Answers1

0

I don't think you can enforce a particular object key sequence in JS. You can, however, create an array of the keys.

const a = {};
const originalSequence = [];
array.forEach(item => {
   a[item.id] = item;
   originalSequence.push(item.id);
})
edo.n
  • 2,184
  • 12
  • 12