简体   繁体   中英

How to map key and values in typescript?

I have the following response that I need to map into a useable format in typescript,

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"}

I've done the below which works, but I think there must be a nicer way.

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];
}

Any help appreciated.

Thanks

You could simplify your code to this:

var vehicles = new Array();

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

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

No need to loop through Vehicles twice.

In general, however, you can use Array.map for data transformation like this. Whether that's always "nicer" is a bit subjective, but this would work:

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

As a rule of thumb, you should only need Array.forEach in JavaScript when you need a side effect, which is not your case; you only need data transformation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM