typescript - 构建可以丰富 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"}]
任何帮助表示赞赏!谢谢
解决方案
您可以像这样初始化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);
推荐阅读
- python - 不明白这个意外的缩进错误
- python-3.x - 分支对话 - 如何继续
- python - 如何删除给定索引集的列表元素?
- wso2 - WSO2 配置(IS 应用程序保护 APIM 端点)
- c# - System.Data.SqlClient.SqlException:''userX' 附近的语法不正确
- c++ - 如何使用可执行文件将我的 C++ 代码合并到我的 Xcode 项目中?
- haskell - 我什么时候应该通过类型类或其他方式定义多态函数?
- sql - 如何使用 SQL 选择多个值
- azure-devops - 是否有变量可以找到最后一次成功部署到某个阶段?
- android - 如何保存多个谷歌地图标记,它们在 Firebase 实时数据库中的位置,并在打开应用程序时再次显示它们