首页 > 解决方案 > 构建可以丰富 Typscript 中对象的函数的最佳方法是什么

问题描述

我需要丰富从后端获取的数据,然后再将其显示在前端,我不确定如何在 Typescript 中做得很好。

我的想法是,我有一个对象数组,其中包含每个对象和 ID,并且我想通过从另一个数组中获取数据来丰富每个对象。我只是不知道如何制作它,所以它很有效。

我的初始对象:

data = [{id:1, done:false}, {id:2, done:true}]

我的功能将丰富我的对象:

function enrich(data){
     foreach data ...
}

还有我的丰富数据存储:

storage = [{id: 1, title: "this will be added", name: "this will be added too"}, {id:2, title="yes add me too to object who has id=2", name="enriched"}]

当然,将数据传递到我的丰富函数的结果是:

data = [{id:1, done:false, title: "this will be added", name: "this will be added too"}, {id:2, done:true, title="yes add me too to object who has id=2", name="enriched"}]

任何帮助表示赞赏!谢谢

标签: typescript

解决方案


您可以像这样初始化enrich函数:

var storage = [{id: 1, title: "this will be added", name: "this will be added too"}, 
               {id:2, title: "yes add me too to object who has id=2", name: "enriched"}];

var data = [{id:1, done:false}, {id:2, done:true}];

function enrich(data){
  for (var d of data) {
    var item = storage.find(x => x.id === d.id);
    
    d.title = item.title;
    d.name = item.name;
  }
}

enrich(data);

console.log(data);


推荐阅读