Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!