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

125
Visualizações
Replace the element with the searched value in an array of objects in Javascript

Having the following array of objects:

const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} }
              ];

I want to write a method that recevies a new object, if the object's id is in the array, it replaces that one with the new one, otherwise it creates a new object.

For example, if the method receives this object: {id: 1, data: {name: 'maria' }}, it will add it to the array, so the array will look like:

const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];

If it receives {id: 3, data: {name: 'jack' }} it should replace the object with id=3 so the result would be:

const input = [ {id: 3, data: {name: 'jack'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];

The code:

function doMagic(input, newObj) {
  if (input.some(el => el.id === newObj.id) {
    // replace it
  } else {
    // add the object to the array
  }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can do it this way:

function doMagic(input, newObj) {
 const i = input.findIndex(element => element.id === newObj.id);
  if (i > -1) input[i] = newObj; 
  else input.push(newObj);
}

const input = [ {id: 3, data: {name: 'jack'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} }
              ];

newObj = {id: 1, data: {name: 'maria' }};
oldObj = {id: 3, data: {name: 'john' }}

doMagic(input, newObj);

console.log(input);

doMagic(input, oldObj);

console.log(input);

about 4 years ago · Juan Pablo Isaza Relatório

0

function doMagic(input, newObj) {
    input.map((el, i, arr) => {
        if (input.some(el => el.id === newObj.id)) {
            input.splice(i, 1, newObj);
        } else {
            input.push(newObj);
        }
    })
}
about 4 years ago · Juan Pablo Isaza Relatório

0

It is possible to use find() to check whether it contains desired object. And if array contains object, then we can update it throug Object.assign() method. If no, then we just push this item to array.

const oneFunction = (arr, objToEdit) => {
  let existingObject = arr.find(f => f.id === objToEdit.id 
      && f.data.name !== objToEdit.name);

  if (existingObject) 
    Object.assign(existingObject, objToEdit);
  else 
    arr.push(objToEdit)  

  return arr;
}

An example:

const input = 
[ 
  {id: 3, data: {name: 'john'} },
  {id: 6, data: {name: 'mike'} },
  {id: 2, data: {name: 'anna'} }
];

const oneFunction = (arr, objToEdit) => {
  let existingObject = arr.find(f => f.id === objToEdit.id && f.data.name !== objToEdit.name);

  if (existingObject) 
    Object.assign(existingObject, objToEdit);
  else 
    arr.push(objToEdit)  

  return arr;
}


let testObject = {id: 3, data: {name: 'john1'}};
console.log(oneFunction(input, testObject))

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