Filter by multidimensional objects with underscore.js

1

How do I filter objects by attribute operations inside json?

var data = Object
entrada_diff: "00:00:00"
entrada_hoje: "00:00:00"
entrada_jornada: "08:00:00"
entrada_status: "PENDENTE"
funcionario_cpf: "06547457656"
funcionario_cracha: "10703"
funcionario_foto: "06547457656.jpeg"
funcionario_marcacoes: "4"
funcionario_nome: "LARISSA"
jornada_total: "08:00:00"
operacoes: object 
 operacao1:'1',
 operacao2:'2'


refeicao_diff: "00:00:00"
refeicao_jornada: "12:00:00"
refeicao_retorno: "00:00:00"
refeicao_saida: "0"
refeicao_seg: "7200"
refeicao_status: "PENDENTE"
saida_diff: "00:00:00"
saida_hoje: "00:00:00"
saida_jornada: "18:00:00"
saida_status: "PENDENTE"
__proto__: Object
, 
Object
, 
Object
, 
Object
, 
Object
, 
Object
, 
Object
]

var set = 'operacao1'; //filtragem

    filtro =  _.filter(data, function(evt) {

    // return true where condition is true for any market
    return _.any(evt.operacoes, function(mkt,op) {

        return op == set;

        });
    });
    
asked by anonymous 09.12.2014 / 21:15

1 answer

1

If I understood correctly what you pasted (it looks like a console exit), and assuming you have an array of objects, it would look like this:

var filtrado = _.filter(data, function(obj){ 
    return  obj.operacoes && obj.operacoes.operacao1 === '1';
});

var data = [{
    foo: 1,
    bar: 1,
    operacoes: {
      operacao1:'1',
      operacao2:'2'
    }
},{
    foo: 1,
    bar: 1,
    operacoes: {
      operacao1:'3',
      operacao2:'4'
    }
}, {
    foo: 1,
    bar: 1,
    operacoes: {
      operacao1:'1',
      operacao2:'3'
    }
}];

var filtrado = _.filter(data, function(obj){ 
    return  obj.operacoes && obj.operacoes.operacao1 === '1';
});

console.log(filtrado);
<script src="https://rawgithub.com/jashkenas/underscore/master/underscore-min.js"></script>
    
09.12.2014 / 22:39