Leonel Matias Domingos
Leonel Matias Domingos

Reputation: 2040

map and filter with lodash 3.10.1

I need to return the atribute label of an array of objects where atribute visible is diferent from false .

ex:

 {
  "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"
}

and the array of objects:

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

I've setup a fiddle. Thanks in advance. https://jsfiddle.net/2ev7fjqh/

Upvotes: 0

Views: 126

Answers (1)

Mulan
Mulan

Reputation: 135217

I need to return the atribute label of an array of objects where atribute visible is diferent from 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' ]


The above iterates through the data multiple times. If you'd like to avoid this, you can transduce

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' ]

Upvotes: 1

Related Questions