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

118
Visualizações
Copy properties using .map() typescript

I wanted to copy selected properties from one object to another based on a condition(key).

//Code

var abc = [{"name":"John", "age":30, "state":"WS", "id": 1}, {"name":"Wille", "age":36, "state":"SFO", "id": 2}, {"name":"Rack", "age":18, "state":"NJ", "id": 3}]

var xyz = [{"weight":69, "height":180, "mobile":4457158, "id": 1}, {"weight":77, "height":178, "mobile":5896854, "id": 2}, {"weight":56, "height":140, "mobile":568574, "id": 3}]

I wanted to copy only the properties (height, mobile) from xyz to abc.

I tried,

const result = abc.map(x=> ({...x, ...xyz.find(y=> y.id === x.id)}));

Even in the above i couldn't copy the entire properties. What went wrong and how can i copy the selected one?

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

0

Maybe just do this in steps:

const result = abc.map((x) => {
  const { height, mobile } = xyz.find((y) => y.id === x.id) || {};
  return { ...x, height, mobile };
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Your code works in js, but in typescript, find could return undefined which means the resulting array will have possibly undefined properties.

interface Person = {
  id: number;
  state: string;
  name: string;
  age: number;
};

interface Stats = {
  id: number;
  weight: number;
  height: number;
  mobile: number;
};

interface Merged extends Person, Stats {}

Consider using find() as Stats if you know the arrays contain the data or wish to ignore that the id may not be found.

about 4 years ago · Juan Pablo Isaza Relatório

0

A one liner and for the sake of the parentheses, you can create an IIFE wrapping the object:

abc.map(x => ({ ...x, ...(({ mobile, height }) => ({ mobile, height }))(xyz.find(y => x.id === y.id)) }));

Basically we spread x, which you're already doing, then spread an IIFE with destructured parameters to return only the data we want, passing our find() results as the arguments.

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