Home>

A question about swapping associative arrays in Javascript.

Although we often see information that uses sort () to replace associative arrays,
I don't know how to swap a specific key + value.

{
key1: {id: 101, name: test1 ...},
key2: {id: 102, name: test2 ...},
key3: {id: 103, name: test3 ...},
key4: {id: 104, name: test4 ...},
}


For example, we want to replace the above array as follows.

{
key1: {id: 101, name: test1 ...},
key3: {id: 103, name: test3 ...},
key2: {id: 102, name: test2 ...},
key4: {id: 104, name: test4 ...},
}

Can you tell me if you know how to do it?

  • Answer # 1

      

    For example, I want to replace the above array as follows.

    Unfortunately JavaScriptObjectisunordered. So you can't manipulate the order from the code.

    Mapguarantees the "order of entry", so reordering allows order control.

Related articles