简体   繁体   English

使用 .map() 复制属性 typescript

[英]Copy properties using .map() typescript

I wanted to copy selected properties from one object to another based on a condition( key ).我想根据条件( key )将选定的属性从一个object复制到另一个。

//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 .我只想将属性( heightmobile )从xyz复制到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?出了什么问题,我该如何复制所选的?

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

Your code works in js, but in typescript, find could return undefined which means the resulting array will have possibly undefined properties.您的代码适用于 js,但在 typescript 中,find 可能会返回 undefined,这意味着生成的数组可能具有未定义的属性。

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.如果您知道 arrays 包含数据或希望忽略可能找不到该 ID,请考虑使用find() as Stats

A one liner and for the sake of the parentheses, you can create an IIFE wrapping the object:一个衬里,为了括号的缘故,您可以创建一个包装 object 的 IIFE:

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.基本上我们传播x ,您已经在做,然后传播带有解构参数的 IIFE 以仅返回我们想要的数据,将我们的find()结果作为 arguments 传递。

 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 }]; function copy(from, to, keys) { const mapped = from.reduce((acc, el) => { return {...acc, [el.id]: el } }, {}); return to.map(el => { const extracted = keys.reduce((acc, k) => ({...acc, [k]: mapped[el.id][k] }), {}); return {...el, ...extracted }; }); } console.log(copy(xyz, abc, ['height', 'weight']));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM