简体   繁体   中英

how to push a new item into a deeply nested Record in immutableJS

I'm trying to push a new item into a deeply nested immutable record.

  const i = Immutable.Record({
    nested: new (Immutable.Record({
      someKey: [{id:1,name:'adam'}, {id:2,name:'steve'}],
    })),
  });
  const myMap = new i;
  const myNewMap = myMap.updateIn(['nested', 'someKey'], (fav)=>    fav.push({id:3,name:'dan'}));

  console.log(myNewMap.toJS());

what I expect is to update the nested list with the new value, but the actual output is

  [object Object] {
  nested: [object Object] {
    someKey: 3
    }
  }

so Im doing something wrong, so how would I go about updating the record with the new value ?

here is the jsbin for the example http://jsbin.com/nipolimuyu/edit?html,js,console

You're missing return statement in a function you pass to updateIn (note that Array.push does NOT return a resulting array!). It should be:

const myNewMap = myMap.updateIn(
  ['nested', 'someKey'], 
  (fav) => {
    fav.push({id:3,name:'dan'})
    return fav
  })

Be careful here.

Your initial obj should all be an immutableJS obj. You can use fromJS().

In your example, you need to add your array as an ImmutableJS list

const i = Immutable.Record({
    nested: new (Immutable.Record({
    someKey: new Immutable.List([{id:1,name:'adam'}, {id:2,name:'steve'}]),
  })),
});
// The bad way, add a normal JS array to an immutableJS Record/map
const i = Immutable.Record({
    nested: new (Immutable.Record({
    someKey: [{id:1,name:'adam'}, {id:2,name:'steve'}],
  })),
});

So at the end you just need to do like you wanted

const myNewMap = myMap.updateIn(['nested', 'someKey'], fav => fav.push({id:3,name:'dan'}));

So now you can use the immutableJS push() function that return a new immutableJS object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM