简体   繁体   English

Javascript:使用第二个数组中的值提取数组中的密钥对值

[英]Javascript: Extract keypair value in array using values from second array

I have a shortlist array that I wish to use to extract the numerical value for the corresponding months from the seasons array.我有一个候选列表数组,我希望用它从季节数组中提取相应月份的数值。

var shortlist = [ "dec", "jan", "feb" ];

var seasons = [{ "jan": "0", "feb": "0", "mar": "0", "apr": "0", "may": "2", "jun": "1", "jul": "1", "aug": "1", "sep": "2", "oct": "0", "nov": "0", "dec": "0" }];

As each value is extracted it will be used for some additional functions.随着每个值的提取,它将用于一些附加功能。

Try using Array#map :尝试使用Array#map

 var shortlist = [ "dec", "jan", "feb" ]; var seasons = [{ "jan": "0", "feb": "0", "mar": "0", "apr": "0", "may": "2", "jun": "1", "jul": "1", "aug": "1", "sep": "2", "oct": "0", "nov": "0", "dec": "0" }]; const result = shortlist.map(e => +seasons[0][e] || 0); console.log(result);

But if you have multiple objects in seasons array, try it like this, it will give you nested arrays:但是如果你在seasons数组中有多个对象,试试这样,它会给你嵌套的 arrays:

 var shortlist = [ "dec", "jan", "feb" ]; var seasons = [ { "jan": "0", "feb": "0", "mar": "0", "apr": "0", "may": "2", "jun": "1", "jul": "1", "aug": "1", "sep": "2", "oct": "0", "nov": "0", "dec": "0" }, { "jan": "2", "feb": "0", "mar": "0", "apr": "0", "may": "2", "jun": "1", "jul": "0", "aug": "1", "sep": "0", "oct": "0", "nov": "0", "dec": "1" }, ]; const result = seasons.map(s => shortlist.map(e => +s[e] || 0)); console.log(result);

 var shortlist = ['dec', 'jan', 'feb']; var seasons = [ { jan: '0', feb: '0', mar: '0', apr: '0', may: '2', jun: '1', jul: '1', aug: '1', sep: '2', oct: '0', nov: '0', dec: '0' } ]; const nums = shortlist.map((mon) => seasons[0][mon]); console.log(nums);

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

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