在打字稿中覆盖数组到索引对象

时间:2020-05-03 14:49:31

标签: javascript arrays json typescript types

我有以下类型的数组。

// https://github.com/svgdotjs/svg.js
// https://github.com/ariutta/svg-pan-zoom
var mySVG = SVG('drawing').size(500, 300);
var nest1 = mySVG.nested().attr('id','svg-container').addClass('svg-container');
var myGroup = nest1.group();
mySVG.rect(20,20).fill('#f33'); // rectangle that should not scale
console.log('mySVG');
console.log(mySVG);
console.log(' --- ');

//myGroup.rect(1000,1000).fill('#eee');
var circle = myGroup.circle(80).move(100,100);

var panZoomInstance = svgPanZoom('#svg-container', {
    panEnabled: true,
    zoomEnabled: true,
    dblClickZoomEnabled: true,
    mouseWheelZoomEnabled: true,
    preventMouseEventsDefault: true,
    zoomScaleSensitivity: 0.2,
    minZoom: 0.5,
    maxZoom: 3,
    fit: false,
    contain: false,
    center: false,
    refreshRate: 'auto',
});

我想将其转换为具有以下类型的索引对象。

interface IArray {
   id: "message1" | "message2" | "message3";
   message: string;
}

const myArray: IArray[] = [
   {
      id: "message1",
      message: "Here is your message 1"
   },
   {
      id: "message2",
      message: "Here is your message 2"
   }
]

我可以编写一个将数组转换为对象的函数。

const myObject = {
   message1: "Here is your message 1",
   message2: "Here is your message 2"
}

但是const myObject: any = {}; myArray.forEach((arrElement) => { myObject[arrElement.id] = arrElement.message; }); 的类型为myObject。而我希望any具有索引类型myObject的类型,具体取决于数组keys的类型。

2 个答案:

答案 0 :(得分:2)

const myArray = [{key: "message1",message: "Here is your message 1"},{key: "message2",message: "Here is your message 2"}]
const result = myArray.reduce((a,b)=>{
  a[b.key]=b.message;
  return a
}, {});
console.log(result);

答案 1 :(得分:1)

您可以使用forEach方法:

JavaScript:

import { ErrorHandler, Injectable, Injector, Inject } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

/**
 * Handle any errors thrown by Angular application
 */
@Injectable()
export class AppErrorHandler extends ErrorHandler {

    constructor(
        @Inject(Injector) private readonly injector: Injector
    ) {
        super();
    }

    handleError(error) {
        console.log("Handling error: " + error);

        this.toastrService.error(error, 'Error!', { onActivateTick: true })

        super.handleError(error);
    }

    /**
     * Need to get ToastrService from injector rather than constructor injection to avoid cyclic dependency error
     * @returns {} 
     */
    private get toastrService(): ToastrService {
        return this.injector.get(ToastrService);
    }

}

TypeScript:

let myArray = [{
    id: "message1",
    message: "Here is your message 1"
  },
  {
    id: "message2",
    message: "Here is your message 2"
  }
];
let myObject = {};
myArray.forEach(item => {
  myObject[item.id] = item.message;
});
console.log(myObject);