Search code examples
javascript

prepend map with new key/value pair


How to prepend a key/value pair to the beginning of a javascript Map object?

var fields = new Map([
    ['product_type', {
        value : 'PRODUCT'
    }],
    ['supplier_product_type', {
        value : 'INTERNAL'
    }]
]);

I want to add a new key to the beginning of the Map so it will end up like this

[
    ['new_key', {
        value : 'new value'
    }],
    ['product_type', {
        value : 'PRODUCT'
    }],
    ['supplier_product_type', {
        value : 'INTERNAL'
    }]
]

Solution

  • I don't believe it's possible. According to the specs on MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), insertion order matters but there are no methods for insers except at the tail.