繁体   English   中英

使用 .map() 复制属性 typescript

[英]Copy properties using .map() typescript

我想根据条件( key )将选定的属性从一个object复制到另一个。

//代码

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}]

我只想将属性( heightmobile )从xyz复制到abc

我试过了,

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

即使在上面我也无法复制整个属性。 出了什么问题,我该如何复制所选的?

也许只需按步骤执行此操作:

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

您的代码适用于 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 {}

如果您知道 arrays 包含数据或希望忽略可能找不到该 ID,请考虑使用find() as Stats

一个衬里,为了括号的缘故,您可以创建一个包装 object 的 IIFE:

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

基本上我们传播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