【问题标题】:how to display object based on matching object id with the id coming from the server如何根据与来自服务器的 id 匹配的对象 ID 显示对象
【发布时间】:2021-05-28 08:57:08
【问题描述】:

我有一个这样的对象数组:

在 FruitModel.ts 中

export interface ColorByFruit{  
    Id : number;
    name : string;
    color : string;
}  
  const Fruits: ColorByFruit[] = [  
     {Id:1, name:"Apple", color:"red"},
     {Id:2, name:"Banana", color:"yellow"}, 
     {Id:3, name:"Peach", color:"Orange"},
     {Id:4, name:"Pineapple", color:"Brown"},
     {Id:5, name:"Blueberry", color:"blue"}, 
]; 

在class.ts中 我将接口导入到类中

然后我从服务器获取包含 ID 的数据,我想将 ID 与 colorFruit Id 匹配,以便显示水果的名称和颜色。

我该怎么做?

【问题讨论】:

  • 你在构造函数中导入接口???根据你说的,试试这个:const names = ServerFruits.filter(x => Fruits.map(y => y.Id).includes(x.Id)).map(x => x.name);
  • 你有办法匹配 ids 吗?根据匹配显示名称和颜色?
  • 注入是错误的,对不起,
  • 如果它解决了您的问题,请接受答案

标签: node.js angularjs angular typescript


【解决方案1】:

要显示名称和颜色,您只需使用地图运算符即可。

假设来自服务器的水果列表设置在一个变量中:ServerFruits

const nameAndColors = ServerFruits.filter(x => Fruits.map(y => y.Id).includes(x.Id)).map(({Id, name}) => ({Id, name})); 

console.log(nameAndColors );

【讨论】:

  • 你从哪里得到过滤功能?
  • 你应该谷歌过滤,你会得到你的答案
猜你喜欢
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 2022-01-11
  • 2013-06-09
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多