Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overwrite an Object inside an Array of Objects

What is the best way to overwrite an object inside an array of objects?

I would like to have only one object per username, in this case in the initial arr Francis has a showMessage to true but userDetails has the same username but different value for the showMessage so I would like to overwrite this last object in the array.

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  { showMessage: true, username: 'Joe' },
  { showMessage: true, username: 'Douglas' },
  { showMessage: false, username: 'Francis' }
]

Current code:

let obj = {};
let arr = [
{showMessage: true, username: "Joe"}, 
{showMessage: true, username: "Douglas"}, 
{showMessage: true, username: "Francis"}  
]

const userDetails = {
  showMessage: false,
  username: 'Francis',
}
objJSON = userDetails

var newData = [...arr, userDetails] 
console.log("newData: ",newData);

>Solution :

Use Object.assign after finding in array the object which matches the username — in order to overwrite/modify the object data with another Object of data

const arr = [
  {showMessage: true, username: "Joe"}, 
  {showMessage: true, username: "Douglas"}, 
  {showMessage: true, username: "Francis"}  
]

const userDetails = {
  showMessage: false,
  username: 'Francis',
};

// Update user data by username (if object is found in array):
const oldDetails = arr.find(user => user.username === userDetails.username);
oldDetails && Object.assign(oldDetails, userDetails);

console.log(arr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading