Filter array of objects by key

0

At the moment it is returning only if the string to be queried is exactly like the object key

let estilos = { "alignContent": [ { "ativo": false } ], "alignItems": [ { "ativo": false } ], "alignSelf": [ { "ativo": false } ], "alignmentBaseline": [ { "ativo": false } ], "all": [ { "ativo": false } ], "animation": [ { "ativo": false } ], "animationDelay": [ { "ativo": false } ], "animationDirection": [ { "ativo": false } ], "animationDuration": [ { "ativo": false } ], "animationFillMode": [ { "ativo": false } ], "animationIterationCount": [ { "ativo": false } ], "animationName": [ { "ativo": false } ], "animationPlayState": [ { "ativo": false } ], "animationTimingFunction": [ { "ativo": false } ], "backfaceVisibility": [ { "ativo": false } ], "background": [ { "ativo": false } ], "backgroundAttachment": [ { "ativo": false } ], "backgroundBlendMode": [ { "ativo": false } ] };

const allowed = 'alignContent';

const filtered = Object.keys(estilos)
  .filter(key => allowed.match(new RegExp(key, 'g')))
  .reduce((obj, key) => {
    obj[key] = estilos[key];
    return obj;
  }, {});
  
console.log(filtered);
    
asked by anonymous 11.03.2018 / 03:22

1 answer

1

allowed and key must have their places inverted, so the query is given for each letter, it is also good to add the toLowerCase method so that the search is done regardless of uppercase or lowercase ...

p>

let estilos = { "alignContent": [ { "ativo": false } ], "alignItems": [ { "ativo": false } ], "alignSelf": [ { "ativo": false } ], "alignmentBaseline": [ { "ativo": false } ], "all": [ { "ativo": false } ], "animation": [ { "ativo": false } ], "animationDelay": [ { "ativo": false } ], "animationDirection": [ { "ativo": false } ], "animationDuration": [ { "ativo": false } ], "animationFillMode": [ { "ativo": false } ], "animationIterationCount": [ { "ativo": false } ], "animationName": [ { "ativo": false } ], "animationPlayState": [ { "ativo": false } ], "animationTimingFunction": [ { "ativo": false } ], "backfaceVisibility": [ { "ativo": false } ], "background": [ { "ativo": false } ], "backgroundAttachment": [ { "ativo": false } ], "backgroundBlendMode": [ { "ativo": false } ] };

const allowed = 'align';

const filtered = Object.keys(estilos)
  .filter(key => key.match( new RegExp(allowed, 'gi')))
  .reduce((obj, key) => {
    obj[key] = estilos[key];
    return obj;
  }, {});
  
console.log(filtered);
    
11.03.2018 / 04:01