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

114
Visualizações
Change the value of aobject based on other array of object value

I have below kind of object

sampleObject = {name : 'John' , age : 34 }

I want to update the age value based on the below array of object value:

sampleArrayOfObject = [{name:'John',age:20},{name:'Mathew',age:23},{name:'Mohammed',age:20}]

The final Output that I want is

updatedOject = {name:'John',age:20}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

const sampleObject = {name : 'John', age : 34 }
const sampleArrayOfObject = [{name:'John',age:20}]
const updatedOject = {...sampleObject, age: sampleArrayOfObject[0].age}
about 4 years ago · Juan Pablo Isaza Relatório

0

I'm not exactly sure how you want the operation to be done, but here is one of the options:

function update(obj, objs) {
  return {
    ...obj,
    age: objs.find(v => v.name === obj.name)?.age ?? obj.age,
  };
}

let updatedOject = update(sampleObject, sampleArrayOfObject);

Here is playground for this option, and here is what you get when if you click "Run":

{
  "name": "John",
  "age": 20
} 

Here is the same option but with proper typings:

type Person = { name: string; age: number }

function update(obj: Person, objs: Person[]): Person {
  return {
    ...obj,
    age: objs.find(v => v.name === obj.name)?.age ?? obj.age,
  };
};

And this is the same code but with generics (I'd say a preferred approach, but don't take this for granted):

function update<T extends { name: string; age: number }>(obj: T, objs: T[]): T {
  return {
    ...obj,
    age: objs.find(v => v.name === obj.name)?.age ?? obj.age,
  };
};
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