3

Here is the code:

    var state = {
    txn:[],
    do:false
}

var newState = Object.assign ({}, state, 
    {
        txn: state.txn.slice(0,0).concat([{txnId:3, b:5}, {txnId:5, b:6}])
    },
    {
        do: !state.do
    }
);

var newState2 = Object.assign ({}, newState, 
{
    txn[0].txnId: 9
});

The first Object.assign works and the newState has the txn array filled with two elements.

The second Object.assign is not working. It says that "[" is an unexpected token.

Any suggestions?

9
  • There is no txn, it's a key in an object, not a variable, it has to be newState.txn Commented Jul 27, 2016 at 10:29
  • but it works in the first Object.assign. Commented Jul 27, 2016 at 10:31
  • No it doesn't, you don't use txn in the first one, you set a key with that name, and use state.txn, never just txn Commented Jul 27, 2016 at 10:32
  • In the first one I used "txn: ….." and this is what i have used it in the second one. Can you please send me the code that you are suggesting? Commented Jul 27, 2016 at 10:35
  • I'd do this -> jsfiddle.net/1b6zxgdm Commented Jul 27, 2016 at 10:36

1 Answer 1

2

It can be achieved this way:

var newState2 = Object.assign ({}, newState, 
{
    txn: newState.txn.map((item, index) => {
      if (index === 0)  {
        return { txnId: item.txnId, b: 9 };
      }
      else {
        return item;
      }
    })
});

http://codepen.io/anon/pen/yJEoJd?editors=1111

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.