0

我有一个以字符串为键,以数组为值的地图。如何向具有相同键的数组添加值?

addToMap(childBundleRowCounter, entityId) {
  if (this.rowCountMap.get(entityId) == undefined) {
    this.rowCountMap.set(entityId, new Array(childBundleRowCounter));
  } else {
    this.rowCountMap.set(entityId, (this.rowCountMap.get(entityId)).push(childBundleRowCounter));
  }
}

4

2 回答 2

2

您的代码中有一个小错误。Array.push()将返回数组的新大小。因此,该数字(大小)将从第二次开始存储为键的值。

您需要一个额外的变量来更新数组元素,如下所示

const rowCountMap = new Map();

function addToMap(childBundleRowCounter, entityId) {
  if (rowCountMap.get(entityId) == undefined) {
    rowCountMap.set(entityId, new Array( childBundleRowCounter));
  } else {
    let t = rowCountMap.get(entityId); // Get the array
    t.push(childBundleRowCounter); // Now push the element
    rowCountMap.set(entityId, t); // Now set the value
  }
}

addToMap('Test One', 1);
addToMap('Test Two', 2);
addToMap('Test Three', 3);
addToMap('Test Four', 1);

for (let [key, value] of rowCountMap) {
  console.log(value)
}

于 2020-11-27T12:02:36.810 回答
1

您没有添加到列表中。使用 find,您可以获得正确的对象,然后使用正确的属性,您可以将值推送到该列表。

this.rowCountMap.find(a=>a.InsertComparisonValue===entityId)
    .InsertNameOfList.push(childBundleRowCounter)

由于使用了地图,因此可以使用以下内容:

 for (const key in this.rowCountMap) {
   if (Object.prototype.hasOwnProperty.call(this.rowCountMap, key)) {
    const element = this.rowCountMap[key];
    if(key===entityId){
      element.push(childBundleRowCounter)
    }
  }
}
于 2020-11-27T11:43:53.293 回答