ES6 Map使用Redux状态的映射和填充减少数组变平

时间:2017-08-15 15:51:35

标签: javascript arrays reactjs ecmascript-6 mapreduce

我正在使用ES6编写React / Redux应用程序,我想要一种有效的方法来映射这些数据:

[
  {total: 50, label: "C1"}, 
  {total: 120, label: "C2"}, 
  {total: 220, label: "C4"}
]

如下所示:

[
  {50, "Category 1"}, 
  {120, "Category 2"}, 
  {0, "Category 3"}, 
  {220, "Category 4"}
  {0, "Category 5"}, 
]

关键是它会使原始数组变平并重新标记标签值,并填充丢失的密钥。

我可以通过一些丑陋的JS迭代它来做到这一点,但我很难通过简单而优雅的减少箭头功能机制来实现这一点,我确信这是可能的。

4 个答案:

答案 0 :(得分:1)

使用.map()

var foo = [{
    total: 50,
    label: "C1"
  },
  {
    total: 120,
    label: "C2"
  },
  {
    total: 220,
    label: "C4"
  }
];

var flatFoo = foo.map((obj) => {
  return [
    obj.total,
    `${obj.label.substr(0, 1)}ategory ${obj.label.substr(1, 1)}`
  ];
});

console.log(flatFoo);

答案 1 :(得分:0)

以下是一些选项......

const data = [
  {total: 50, label: "C1"}, 
  {total: 120, label: "C2"}, 
  {total: 220, label: "C4"}
];

const stripChars = s => (s || '').replace(/[a-z]/i, '');


function fillTo(limit, data) {

  return Array
    .from({length: limit}, (_, i) => (
      data.find(o => stripChars(o.label) == i) ||
      { total: 0, label: `C${i}` }
    ))
  ;
}


const toMap = data => data.reduce(
  (res, $1) => Object.assign(res, {
    [$1.total]: `Category ${stripChars($1.label)}`
  }), Object.create(null)
);

const pairwise = data => data.map(
  $1 => [$1.total, `Category ${stripChars($1.label)}`]
);

console.log('fillTo', fillTo(6, data));
console.log('toMap', toMap(data));
console.log('pairwise', pairwise(data));

/**
 * 1. fill the array
 * 2. chose your transformer 
 * 
 * const d = fillTo(6, data);
 * console.log(pairwise(d));
**/

答案 2 :(得分:0)

使用Array.prototype.reduce创建哈希表以将缺少的键填充到数组数组 - 请参阅下面的演示:



var arr = [{total: 50, label: "C1"},{total: 120, label: "C2"},{total: 220, label: "C4"}];

// create a hash table first
var hash = arr.reduce(function(p,c){
  var key = c.label.replace(/[^\d]/g,'');
  p[key] = c;
  // largest key
  p['count'] = (+key > (p['count'] || 0)) ? +key : p['count'];
  return p;
}, Object.create(null));

// accumulate the result
var result = [];
for(var i = 0; i < hash['count']; i++) {
  var el = hash[i + 1] || {};
  result.push([el.total || 0, 'Category '+ (i+1)]);
}
console.log(result);
&#13;
.as-console-wrapper {top: 0;max-height: 100%!important;}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以先对原始数组进行排序,以获得最小值和最大值,然后使用循环添加缺少的元素。

&#13;
&#13;
var data = [
  {total: 220, label: "C14"},
  {total: 50, label: "C3"}, 
  {total: 120, label: "C10"}, 
  {total: 220, label: "C7"}
]


data.sort((a, b) => a.label.slice(1) - b.label.slice(1))
var result = [];

data.forEach(function(e, i) {
  var n = e.label.slice(1);
  var next = data[i + 1]
  result.push([e.total, 'Category ' + n]);

  if (next) {
    for (var j = n; j < +(next.label.slice(1) - 1); j++) {
      result.push([0, 'Category ' + (+j + 1)])
    }
  }
})

console.log(JSON.stringify(result, 0, 4))
&#13;
&#13;
&#13;