2017-11-25 104 views
-3

假设我有访问内JS对象随着打字稿

data = { 
    result: [ 
     { 
      id: '001', 
      name: 'Caio B', 
      address: { 
       address: 'sau paulo', 
       city: 'sau paulo', 
       country: 'brazil', 
      }, 
     }, 
      { 
      id: '002', 
      name: 'Gustavo H', 
      address: { 
       address: 'Rio', 
       city: 'Rio', 
       country: 'brazil', 
      }, 
     }, 
    ], 
} 

下面的数据集,我想从地址对象只提取了全国各地,并与ID和名称,以便转换后的结果结合起来会看起来如下:

data = { 
    result: [ 
     { 
      id: '001', 
      name: 'Caio B' 
      country: 'brazil', 
     }, 
      { 
      id: '002', 
      name: 'Gustavo H', 
      country: 'brazil', 
     }, 
    ], 
} 

我该如何使用最少的处理来实现这种打字稿?

+0

我想知道,要在HTML或TS类使用它? –

+0

学习如何在打字稿前用普通的javascript来做到这一点。 – evolutionxbox

回答

0

你可以用普通的JavaScript来做到这一点。迭代项目并筛选出不需要的属性。事情是这样的:

function process(items) { 
 
     var data = {}; 
 
     data.result = items.map(function (item) { 
 
     \t return { 
 
     \t id: item.id, 
 
      name: item.name, 
 
      country: item.address.country 
 
     } 
 
     }) 
 
     return data; 
 
    } 
 
    var data = { 
 
    "result": [ 
 
    { 
 
     "id": "001", 
 
     "name": "Caio B", 
 
     "address": { 
 
     "address": "sau paulo", 
 
     "city": "sau paulo", 
 
     "country": "brazil" 
 
    } 
 
    }, 
 
    { 
 
     "id": "002", 
 
     "name": "Gustavo H", 
 
     "address": { 
 
     "address": "Rio", 
 
     "city": "Rio", 
 
     "country": "brazil" 
 
     } 
 
    } 
 
    ] 
 
}; 
 
    
 
var data2 = process(data.result); 
 
    console.log(data2);

1

如果你是一个面向对象的情人 在TS

class Country{ 
public id:string = ''; 
    public name:string = ''; 
    public country:string = ''; 
constructor(I){ 
    this.id = I.id; 
    this.name =I.name; 
    this.country =I.address.country; 
    } 
} 

创建国家一类现在使用一个for循环输入数据

public Countries:Array<Country> =[]; 

在您收到的函数中Ë数据

for(let i = 0; i< data.length;i++) 
this.Countries.push(new Country(data[i])) 
0

对于每个结果,分配国家和删除地址:

data = { 
 
    result: [{ 
 
     id: '001', 
 
     name: 'Caio B', 
 
     address: { 
 
     address: 'sau paulo', 
 
     city: 'sau paulo', 
 
     country: 'brazil', 
 
     }, 
 
    }, 
 
    { 
 
     id: '002', 
 
     name: 'Gustavo H', 
 
     address: { 
 
     address: 'Rio', 
 
     city: 'Rio', 
 
     country: 'brazil', 
 
     }, 
 
    }, 
 
    ], 
 
} 
 

 
data.result.forEach(o => { o['country'] = o.address.country; delete o.address }) 
 

 
console.log(data)