用lodash 3.10.1映射和过滤

时间:2017-06-19 22:48:20

标签: object dictionary filter functional-programming lodash

我需要返回一个对象数组的属性label,其中属性visible与false不同。

例如:

 {
  "EMPRESA": "CMIP",
  "CD_MAQ": "EXE03",
  "DT_INI_MAQ": "1900-01-01",
  "DSP_MAQ": "EXE03",
  "DSR_MAQ": "EXE03",
  "RACIO_PARAGEM": null,
  "ID_MAGNITUDE": "101",
  "DT_INI_DM": "1900-01-01",
  "DT_FIM": null,
  "DT_RowId": "row_CMIPEXE031900-01-01",
  "DESIGEMPRESA": "CMIP",
  "DSP_MAGNITUDE": "Metros"
}

和对象数组:

var tableColumns=  [
            {
                "targets": 0,
                "title": "", //Datatables
                "label": "", //Editor
                "data": 'EMPRESA',
                "name": 'EMPRESA',
                "width": "",
                "type": "hidden", //Editor
                "visible": false, //DataTables
                "defaultContent": "",
                "bSearchable": false,
                "orderable": false
            }, {....

我设置了一个小提琴。提前致谢。 https://jsfiddle.net/2ev7fjqh/

1 个答案:

答案 0 :(得分:1)

  

我需要返回属性labelvisible不同的对象数组的属性false

const data = [
  { label: 'A', visible: false },
  { label: 'B', visible: true },
  { label: 'C', visible: true },
  { label: 'D', visible: false },
  { label: 'E', visible: true }
]

const result =
  data
    .filter(x => x.visible !== false)
    .map(x => x.label)
    
console.log(result)
// [ 'B', 'C', 'E' ]

以上内容多次迭代数据。如果您想避免这种情况,可以转换

const data = [
  { label: 'A', visible: false },
  { label: 'B', visible: true },
  { label: 'C', visible: true },
  { label: 'D', visible: false },
  { label: 'E', visible: true }
]

const mapper = f =>
  k => (acc, x) => k (acc, f (x))
  
const filterer = p =>
  k => (acc, x) => p (x) ? k (acc, x) : acc
  
const tcomp = (tf, tg) =>
  k => tf (tg (k))
  
const concat = (xs, ys) =>
  xs.concat(ys)
  
const transduce = (...ts) => xs =>
  xs.reduce (ts.reduce (tcomp, k => k) (concat), [])
  
const visibleLabels =
  transduce (filterer (x => x.visible !== false),
             mapper (x => x.label))
            
console.log (visibleLabels (data))
// [ 'B', 'C', 'E' ]