javascript如何动态地将子字典附加到父字典

我有一个像这样的Javascript对象:


const childDict = {

  address: {

    zip: "GGHG654",

    city: "Morocco",

    number: 40

  }

}

我想在这样的循环中动态地将它添加到另一个父字典中:


let parentDict = {}


for(let i = 0 ; i < 3; i++){

  parentDict["place" + i] = childDict

}

所以最后我得到了一个像这样的字典:


{

  place0: {

    address: {

      zip: "GGHG654",

      city: "Morocco",

      number: 40

    }

  },

  place1: {

    address: {

      zip: "GGHG654",

      city: "Morocco",

      number: 40

    }

  }

}

然而,for循环给了我一个编译错误:


Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.

  No index signature with a parameter of type 'string' was found on type '{}'.


慕工程0101907
浏览 205回答 3
3回答

九州编程

let&nbsp;parentDict&nbsp;=&nbsp;{}这没有明确设置导致此问题的类型。尝试提供any如下类型:let&nbsp;parentDict:any&nbsp;=&nbsp;{}或者,更准确地说:let&nbsp;parentDict:{[key:&nbsp;string]:&nbsp;object}&nbsp;=&nbsp;{}

Smart猫小萌

您只需向父字典添加适当的接口,因为打字稿会根据初始值自动分配类型,初始值没有任何键interface IParentDict {&nbsp; &nbsp; [key: string]: any; // possibly change any to the typeof child dict}const parentDict: IParentDict = {};

慕桂英546537

像这样试试let parentDict: any = {};另一种选择可能是以更正确的方式指定类型,例如let parentDict: {[key: string]: any} = {};另一种骇人听闻的方式是let parentDict = {}for(let i = 0 ; i < 3; i++){&nbsp; &nbsp; (parentDict as any)["place" + i] = childDict}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript