Home > Blockchain >  Get all keys from a Map() according to their property value in Javascript
Get all keys from a Map() according to their property value in Javascript

Time:08-30

I am currently trying to get all keys from a Map() structure in JS/TS which met a specific criteria, so I am able to change a value of another property of the same elements:

const map1 = new Map();

map1.set('a', {price:1, stock:true});
map1.set('b', {price:3, stock:false});
map1.set('c', {price:5, stock:true});

How can I get to know, for example, all keys where price > 1? The output could be an array of anything else that can be used to handle the map and change its properties according to the respective constraint. In case I would like to change all 'stock' properties to false when price > 1.

Thanks!

CodePudding user response:

[...map1].filter should do

const map1 = new Map();

map1.set('a', {price:1, stock:true});
map1.set('b', {price:3, stock:false});
map1.set('c', {price:5, stock:true});

const map2 = new Map([ ...map1 ].filter(([key, value]) => value.price > 3))

console.log([...map2])

CodePudding user response:

You could iterate the map directly and apply update if necessary.

const map1 = new Map([['a', { price: 1, stock: true }], ['b', { price: 3, stock: false }], ['c', { price: 5, stock: true }]]);

map1.forEach(value => {
    if (value.price > 1) value.stock = false;
});

console.log([...map1]);

  • Related