使用Typescript访问内部JS对象

时间:2017-11-25 14:14:14

标签: javascript json typescript

假设我有以下数据集

app.use(function(req,res,next) {
    if(req.headers["x-forwarded-proto"] == "http") {
        console.log('Request was HTTP');
        /* return ??*/ res.redirect("https://" + req.headers.host + req.url);
        // return or next() or nothing ??.
    } else {
        console.log('Request was not HTTP');
        return next();
    } 
});

我想从地址对象中仅提取国家/地区,并将其与ID和名称相结合,以便转换后的结果如下所示:

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

如何使用最少的处理在Typescript中实现这一点?

3 个答案:

答案 0 :(得分:1)

如果你是OOP爱好者 在ts

中为Country创建一个类
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]))

答案 1 :(得分:0)

您可以使用纯JavaScript执行此操作。迭代这些项目并过滤掉您不需要的属性。像这样:

&#13;
&#13;
 function process(items) {
      var data = {};
      data.result = items.map(function (item) {
      	return {
        	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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

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

&#13;
&#13;
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)
&#13;
&#13;
&#13;