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

标签 javascript typescript dictionary javascript-objects

我有一个像这样的 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 '{}'.

最佳答案

您只需向父字典添加适当的接口(interface),因为 typescript 会根据初始值自动分配类型,该初始值没有任何键

interface IParentDict {
    [key: string]: any; // possibly change any to the typeof child dict
}
const parentDict: IParentDict = {};

关于javascript如何动态地将子字典附加到父字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737087/

相关文章:

javascript - 带有 TypeScript 的 JQWidget

python - 将具有不同数量参数的函数存储在字典中

javascript - TypeError : object is not a function - Javascript, ExtJS、Jasmine 和 TypeError:将循环结构转换为 JSON

java - 未显示 ActionError

asp.net-mvc - 更新 Bootstrap 后发生 "The build task could not find node.exe which is required to run the TypeScript compiler."

typescript - 如何使用内部带有 "this"的箭头函数修复此 @typescript-eslint 警告?

javascript - 如何在javascript中增加数据索引

javascript - 在 React 中将表行添加到表中

c# - 如何在 foreach 循环中访问嵌套的 Dictionary<> 对象

function - Swift func - 不符合协议(protocol) "Boolean Type"