Javascript数组和对象比较

时间:2018-08-06 11:43:06

标签: javascript arrays loops object

我正在尝试存储一年的最高和最低温度。

所以我有一个数组和一个像这样的对象。

var Months =['January','February','March','April','May','June','July','August','September','October','November','December'];  

result[0] = {January: 26.2, February: 25.9, March: 25.7, April: 23.4, May: 19.3, June: 15.9, July: 15.4, August: 16, September: 21.3, October: 24.8, November: 26.6, December: 26.6,Type: "Min"}

result[1] = {January: 36.3, February: 35.9, March: 36, April: 36.7, May: 34.2, June: 31.4, July: 32, August: 34, September: 37.8, October: 39.5, November: 39.8, December: 37.8,Type: "Max"}.

这是我拥有的数据,现在我想要两个不同的数组以适当的顺序存储数据。 (从1月-12月开始)

例如:

var min = [26.2,25.9,25.7,23.4,19.3,15.9,15.4,16,21.3,24.8,26.6,26.6]
var max = [36.3,35.9,36,36.7,34.2,31.4,32,34,37.8,39.5,39.8,37.8]

如何从对象中提取数据并确保顺序与“月”相同?另外,我还需要在新数组中删除“最小/最大”的“类型”。

3 个答案:

答案 0 :(得分:5)

您可以简单地使用 .map() method 来映射EclipseLink对象中的相关月份值并将它们分配给resultmin变量

这应该是您的代码:

max

演示:

var [min, max] = result.map(r => Months.map(m => {
  return r[m]
}));

答案 1 :(得分:1)

您不需要任何循环。只需使用Object.values()pop(),以便从数组中删除值为Type的最后一个元素。

var Months  = ['January','February','March','April','May','June','July','August','September','October','November','December'];  

var result = [{January: 26.2, February: 25.9, March: 25.7, April: 23.4, May: 19.3, June: 15.9, July: 15.4, August: 16, September: 21.3, October: 24.8, November: 26.6, December: 26.6,Type: "Min"},
 {January: 36.3, February: 35.9, March: 36, April: 36.7, May: 34.2, June: 31.4, July: 32, August: 34, September: 37.8, October: 39.5, November: 39.8, December: 37.8,Type: "Max"}];
 
 var min = Object.values(result[0]);
 min.pop();
 var max = Object.values(result[1]);
 max.pop();
 console.log(min);
 console.log(max);

答案 2 :(得分:0)

您可以使用months数组的有序元素来顺序访问每个result对象的相应月份键。由于您的months数组不包含Type元素,因此该键将被忽略。

var Months =['January','February','March','April','May','June','July','August','September','October','November','December'];
var result = []
result[0] = {January: 26.2, February: 25.9, March: 25.7, April: 23.4, May: 19.3, June: 15.9, July: 15.4, August: 16, September: 21.3, October: 24.8, November: 26.6, December: 26.6,Type: "Min"}
result[1] = {January: 36.3, February: 35.9, March: 36, April: 36.7, May: 34.2, June: 31.4, July: 32, August: 34, September: 37.8, October: 39.5, November: 39.8, December: 37.8,Type: "Max"}

var min = []
var max = []

for (let month of Months) {
  min.push(result[0][month])
  max.push(result[1][month])
}

console.log(min, max)