Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.assign to update the array element in an object

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?

like image 531
sauram1234 Avatar asked Mar 08 '26 02:03

sauram1234


1 Answers

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

like image 60
berliner Avatar answered Mar 09 '26 14:03

berliner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!