Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

immutable js update a key in Map

So I have an Immutable js map:

{
 title: "item 1",
 title2: "item 2",
 title3: "item 3"
}

I want to update the keys, so it will become:

{
  new title: "item 1",
  title2: "item 2",
  title3: "item 3"
}

so far with update() and set() I can only update the values? Is it possilbe to update the key or do I need to convert it before I can update the keys?

like image 943
Wilbur Robertson Avatar asked Nov 29 '22 23:11

Wilbur Robertson


2 Answers

you can use mapKeys as :

var map = Immutable.Map({
  new title: "item 1",
  title2: "item 2",
  title3: "item 3"
});

map = map.mapKeys(k => {
  if (k === "title1") 
    return "newTitle";
  return k;
});
like image 144
erdysson Avatar answered Dec 01 '22 14:12

erdysson


another, more direct, approach is to use delete

var map = Immutable.Map({
  title: "item 1",
  title2: "item 2",
  title3: "item 3"
});

map = map.set('new title', "item 1")
    .delete('title');

or

map = map.set('new title', map.get('title'))
    .delete('title');
like image 20
Seth McClaine Avatar answered Dec 01 '22 12:12

Seth McClaine