Search code examples
javascriptecmascript-6ecmascript-2016

How to change few key value pairs in ES6/ES7


I have a lot of key value pairs in my object and I wanted to only change some of it. In my case below, i only wanted to change the place. The values to be submitted are all of them.

Object

values: { username: 'johndoe', password: 123, contact_no: '18323223', place: 'LA' }

CODE

onSubmit: (values) => {

  const formData = (values) => {
    return Object.assign({}, values, {
      place: 'Iowa',
    });
  };
  console.log(formData);

},

Solution

  • If you want to update a property in an object, you can use one of these two techniques:

    values = { username: 'johndoe', password: 123, contact_no: '18323223', place: 'LA' }
    //method 1
    values['place'] = 'Iowa';
    console.log(values);
    //method 2
    values = {...values, place:'Iowa1'};
    console.log(values);