简体   繁体   中英

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. 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:

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". While Array.from pulls every key from that iterator, it passes it to the callback function. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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