[SOLVED] Copy properties using .map() typescript

Issue

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?

Solution

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

Answered By – Prayx

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *