Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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:

[
  { 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);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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);

about 4 years ago · Juan Pablo Isaza Relatório

0

I would typically find the index with that username, if it exists, splice the new object into that position, if not, splice the new object onto the end

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

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

const set = (obj) => {
    const i = arr.findIndex(el => el.username === obj.username);
    arr.splice(i === -1 ? arr.length : i, i === -1 ? 0 : 1, obj);
    return arr;
}

var newData = set(userDetails)
console.log("newData: ",newData);

Which works both for adding a new object, and editing an existing

However, I'd generally avoid the issue entirely by using the username as a key, instead of an array:

let arr = {
    Joe: {showMessage: true, username: "Joe"}, 
    Douglas: {showMessage: true, username: "Douglas"}, 
    Francis: {showMessage: true, username: "Francis"}  
}

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

const set = (obj) => {
   arr[obj.username] = obj
}

set(userDetails)
console.log("newData: ", Object.values(arr));

about 4 years ago · Juan Pablo Isaza Relatório

0

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

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

const newData = [...arr];

for (let i = 0; i < newData.length; i++) {
    if (arr[i].username == userDetails.username) {
        newData[i] = userDetails;
    }
}

console.log("newData: ", newData);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda