如何在打字稿中映射键和值?

时间:2019-01-08 19:49:29

标签: javascript arrays typescript mapping

我有以下回应,我需要将其映射为打字稿中可用的格式,

response => {

    Vehicles:
        BMW: Array(3)
            0: {ModelName: "M3", ModelUid: "14711"}
            1: {ModelName: "X3", ModelUid: "14712"}
            2: {ModelName: "Z4", ModelUid: "14713"}

        Aston Martin: Array(4)
            0: {ModelName: "DBS", ModelUid: "14742"}
            1: {ModelName: "DB9", ModelUid: "14743"}
            2: {ModelName: "V12 Vantage", ModelUid: "14744"}
            3: {ModelName: "Virage", ModelUid: "14745"}

我已经完成了下面的工作,但是我认为必须有更好的方法。

var vehicles = new Array();

var keys = Object.keys(response.Vehicles);

keys.forEach(key => {
    vehicles.push({ Manufacturer: key, Models: [] });
});

for (var i = 0; i < vehicles.length; i++)
{
    var name = vehicles[i].Manufacturer;
    vehicles[i].Models = response.Vehicles[name];
}

任何帮助表示赞赏。

谢谢

1 个答案:

答案 0 :(得分:0)

可以将您的代码简化为:

var vehicles = new Array();

var keys = Object.keys(response.Vehicles);

keys.forEach(key => {
    vehicles.push({ Manufacturer: key, Models: response.Vehicles[name] });
});

无需遍历Vehicles两次。

但是,通常,您可以像这样使用Array.map进行数据转换。是否总是“更细”有点主观,但这会起作用:

const vehicles = Object.keys(response.Vehicles).map((vehicleKey) => {
    return {
        Manufacturer: vehicleKey,
        Models: response.Vehicles[vehicleKey],
    }
});

根据经验,在需要副作用的情况下,只需要在JavaScript中使用Array.forEach,而情况并非如此。您只需要数据转换。