在Highcharts reduce方法中将对象参数与​​数组值组合在一起

时间:2018-04-06 17:16:42

标签: javascript arrays angularjs highcharts

抱歉,由于英语不是我的第一语言,所以不知道如何准确搜索。我想要做的是将数组值组合到一个对象参数。我使用highcharts reduce方法来显示单词的出现我的对象是obj{}

var data = Highcharts.reduce(series, function(arr, word) {
  var obj = Highcharts.find(arr, function(obj) {
    return obj.name === word;
  });
  obj = {
    name: word,
    weight: sortWeight()
  };
  arr.push(obj);
  console.log(obj);
  return arr;
}, []);

sortWeight函数只是一个for循环

function sortWeight() {
            for (var i =0; i < sortedWeights.length; i++) {
                return sortedWeights [i];
            }
 }

我面临的问题是我总是得到的答案,这个策略只是数组的第一个元素。 因此,排序的权重数组类似于sortedWeights =  [28, 17, 15, 15, 15, 12, 12, 11, 11, 10, 9, 8, 8, 8, 7, 7, 6, 6, 6, 6],但我的对象obj的权重始终为数组的第一个值。如何更改权重值,以便第二个单词的值为17第三个15,依此类推。系列数组就像["great", "friendly", "good", "beautiful", "nice", "wonderful", "clean", "excellent", "helpful", "the best", "better", "comfortable", "front desk", "amazing", "perfect", "awesome", "amenities", "complaint", "gorgeous", "definitely stay"]现在我想得到的答案,即数据数组[{name:great, weight:28}, {name:friendly, weight:17}, {name:good, weight:15}, {name:beautiful, weight:15}....]

1 个答案:

答案 0 :(得分:1)

使用Array.map()迭代series,并使用索引(i)从sortedWeights获取匹配的数字:

&#13;
&#13;
var series = ["great", "friendly", "good", "beautiful", "nice", "wonderful", "clean", "excellent", "helpful", "the best", "better", "comfortable", "front desk", "amazing", "perfect", "awesome", "amenities", "complaint", "gorgeous", "definitely stay"];
var sortedWeights =  [28, 17, 15, 15, 15, 12, 12, 11, 11, 10, 9, 8, 8, 8, 7, 7, 6, 6, 6, 6];

var result = series.map(function(word, i) {
  return {
    name: word,
    weight: sortedWeights[i]
  };
});

console.log(result);
&#13;
&#13;
&#13;