什么是构建可丰富打字稿中对象的功能的最佳方法

问题描述 投票:1回答:2

我需要丰富从后端获取的数据,然后再在前端显示它,并且不确定如何在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"}]

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

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
2个回答
0
投票

您可以像这样初始化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);

0
投票

在下面的示例中,我们正在调用一个函数,该函数将返回一个包含您要查找的结果的新数组。

注意:我们不会更改任何数据;反对@Tân

的有效答案

const 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',
}];

/**
 * Enrich the data looking at the storage
 */
function enrich(toEnrich) {
  // Look for the data on the storage for each data in the toEnrich array
  // Map will create a new array based on the toEnrich data
  // Every data we return here will be a part of the new array
  return toEnrich.map(x => ({
    // Build a new object
    
    // We copy all the keys from the toEnrich array
    ...x,

    // We look for the data in storage and copy it into the new object
    // The || is here to prevent the fact we do not find the appropriate data
    // in storage array
    ...(storage.find(y => y.id === x.id) || {}),
  }));
}

console.log(enrich([{
  id: 1,
  done: false,
}, {
  id: 2,
  done: true,
}, {
  id: 3,
  done: true,
}]));
© www.soinside.com 2019 - 2024. All rights reserved.