简体   繁体   English

如何在JavaScript中使用数组填充地图对象的值?

[英]How to fill the Values of a Map Object with an Array in JavaScript?

I have an object and an array. 我有一个对象和一个数组。 Both the array and the object are 24 pairs/index long. 数组和对象均为24对/索引长。 How do I substitute the values of the object with the values of the array? 如何用数组的值替换对象的值? This does not work: 这不起作用:

for (let keys of zeitFaktor.keys() ){
    for (ix = 0; ix < 24; ix++){
        zeitFaktor.set(keys, patientenFaktoren[ix]);
    };
};

Here all of the keys are paired with the first value of the array. 在这里,所有键都与数组的第一个值配对。 Does anybody have an idea how to solve this? 有人知道如何解决这个问题吗? Any help is highly appreciated. 非常感谢您的帮助。

If you are sure zeitFaktor contains the same number of elements as patientenFaktoren , you can simply use its keys in a single-loop and iteration: 如果您确定zeitFaktor包含相同数量的元素的patientenFaktoren ,你可以简单地使用它的键的单回路和迭代:

const keys = zeitFaktor.keys();

for (let ix = 0; ix < 24; ix++) {
  const key = keys.next().value;
  zeitFaktor.set(key, patientenFaktoren[ix]);
}

You would only need one loop, not a nested one. 您只需要一个循环,而无需嵌套循环。 Go for a loop mechanism that also gives you the index of the key: 寻找一种循环机制,该机制还为您提供密钥的索引:

Array.from(zeitFaktor.keys(), (key, ix) =>
    zeitFaktor.set(key, patientenFaktoren[ix])
);

 const zeitFaktor = new Map([['a', 1], ['b', 1], ['c', 1], ['d', 1]]); const patientenFaktoren = [15, 37, -23, 6]; Array.from(zeitFaktor.keys(), (key, ix) => zeitFaktor.set(key, patientenFaktoren[ix]) ); console.log([...zeitFaktor]); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Explanation 说明

zeitFaktor.keys() returns an iterator, which Array.from "consumes". zeitFaktor.keys()返回一个迭代器, Array.fromArray.from ”。 While Array.from pulls every key from that iterator, it passes it to the callback function. 虽然Array.from从该迭代器中提取每个键,但它会将其传递给回调函数。 That callback function will get both the key and the index order in which it occurs. 该回调函数将同时获取键和索引发生的顺序。

The callback function is written as an arrow function ( => ), using the short expression syntax (no braces). 使用短表达式语法(无花括号),将回调函数编写为箭头函数( => )。 This means that zeitFaktor.set(key, patientenFaktoren[ix]) is evaluated for each key, and this will modify the Map as intended. 这意味着将为每个密钥评估zeitFaktor.set(key, patientenFaktoren[ix]) ,这将按预期修改Map。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM