Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

Using a for loop to push items onto a Map in JavaScript reverses the order of the array

Why is the order in the below code reversed in the array that is created?

let conns =  [
    {"jobId":"BPOM","id":{"makeupUID":"4"}},
    {"jobId":"BPOM","id":{"makeupUID":"3"}},
    {"jobId":"BPOM","id":{"makeupUID":"2"}},
    {"jobId":"BPOM","id":{"makeupUID":"1"}}];


console.log(`Before: ${JSON.stringify(conns)}`)
    let unique = new Map();
    for (let item of conns) {
      unique[item.id.makeupUID] = item;
    }
    
    this._allConnections = Object.values(unique);
    console.log(`After: ${JSON.stringify(this._allConnections)}`)
question from:https://stackoverflow.com/questions/65617181/using-a-for-loop-to-push-items-onto-a-map-in-javascript-reverses-the-order-of-th

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As people by now pointed out in the comments, you need to use .set() to insert elements into the map, and .values to get them out again. Otherwise you are actually butchering your Map object with additional fields that don't belong there, but certainly don't do want you want, namely use the properties of Map.

let conns =  [
  {"jobId":"BPOM","id":{"makeupUID":"4"}},
  {"jobId":"BPOM","id":{"makeupUID":"3"}},
  {"jobId":"BPOM","id":{"makeupUID":"2"}},
  {"jobId":"BPOM","id":{"makeupUID":"1"}}];
  
  
console.log(`Before: ${JSON.stringify(conns)}`)
let unique = new Map();
for (let item of conns) {
  unique.set(item.id.makeupUID, item);
}

this._allConnections = Array.from(unique.values());
console.log(`After: ${JSON.stringify(this._allConnections)}`)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...