0

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!

2
  • please specify a single result. do you want to update the map or get an array of objects? Commented Aug 29, 2022 at 21:45
  • I actually want to update the map specific property if the condition is met. I've just mentioned the array example since I imagine that one alternative would be to handle an array from it. However, the objective is to update the map indeed. Commented Aug 29, 2022 at 22:15

2 Answers 2

1

[...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])

Sign up to request clarification or add additional context in comments.

1 Comment

This could be one approach indeed. However, looks like it returns an array which would require some additional iterations to allow to modify the Map properties.
0

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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.