如何将对象列表映射到字典或地图?

时间:2018-09-12 11:28:30

标签: typescript

我正在尝试创建一个childDict供以后使用。实际上,我不仅尝试,而且还成功。

有效

const childDict = new Map(
  this.voteCards.toArray().map(card => {
    return [card.placeInfo.id, card.placeInfo];
  })
);

但是,口译员并不高兴。我会避免给您错误消息,只是类型冲突。

enter image description here

那么如何将列表映射到字典或地图上?

3 个答案:

答案 0 :(得分:0)

Map类型在这里(对我来说)https://github.com/Microsoft/TypeScript/blob/master/src/lib/es2015.collection.d.ts#L12

这是tsconfig.json中的这些lib设置:

"lib": [
  "es2016",
  "es2017.intl",
  "es2017.object",
  "es2017.string",
  "es2017.typedarrays",
  "esnext.asynciterable",
  "dom"
]

您可能遇到的问题是,map函数返回的内容不是ReadOnly数组。

答案 1 :(得分:0)

TypeScript对于元组不是很好。有人注意到了这个问题,并提交了一个错误8936,但已将其关闭

  

没有上下文类型就永远不能推断出元组类型。

因此,您可以使用map.set()来避免这种类型的错误。

var voteCardsArray = [
    { placeInfo: { id: 42, desc: 'stuff 42' } },
    { placeInfo: { id: 65, desc: 'stuff 65' } },
    { placeInfo: { id: 89, desc: 'stuff 89' } },
];

const childDict = new Map();

for (let card of voteCardsArray) {
    childDict.set(card.placeInfo.id, card.placeInfo);
}

// Example usage
const card42 = childDict.get(42);
console.log(card42);

答案 2 :(得分:0)

这是一种在一行中将对象数组转换为字典的方法:

var voteCardsArray = [
    { placeInfo: { id: 42, desc: 'stuff 42' } },
    { placeInfo: { id: 65, desc: 'stuff 65' } },
    { placeInfo: { id: 89, desc: 'stuff 89' } },
];

var res = Object.assign({}, ...voteCardsArray.map(card => ({[card.placeInfo.id]: card.placeInfo})));

console.log(res)
相关问题