0

I'd like to create a new array with information filtered from a nested object with unknown keys.

The data comes from CUPS API and the keys are printer names. I'd like to filter on for example 'printer-state' === 3.

const data = {
    'Expedition': {
        'printer-is-shared': false,
        'printer-state': 4,
        'printer-state-message': '',
        'printer-state-reasons': ['none'],
    },
    'Serverroom': {
        'printer-is-shared': false,
        'printer-state': 3,
        'printer-state-message': '',
        'printer-state-reasons': ['none'],
    }
}

Thanks

I've tried Array.filter() but couldn't get it to work.

isherwood
  • 58,414
  • 16
  • 114
  • 157

1 Answers1

0

    const data = {
    'Expedition': {
        'printer-is-shared': false,
        'printer-state': 4,
        'printer-state-message': '',
        'printer-state-reasons': ['none'],
    },
    'Serverroom': {
        'printer-is-shared': false,
        'printer-state': 3,
        'printer-state-message': '',
        'printer-state-reasons': ['none'],
    }
}
const filterObjectByKeyValue = (obj, key, value) => {
      return Object.keys(obj)
        .filter(k => obj[k][key] === value)
        .reduce((res, k) => ((res[k] = obj[k]), res), {});
};

console.log(filterObjectByKeyValue(data,'printer-state',3))
Taha Azzabi
  • 2,392
  • 22
  • 31