Skip to content Skip to sidebar Skip to footer

Find Keys In Nested Array Of Objects

I receive multiple JSONs from an API (17 API calls with Promise.all() ). For example [ { key: value, key: value, key: value, key: value, values: [ {

Solution 1:

You can use below function to get all values stored at the key you specify:

function getKeyValues(arr, key) {
    return arr.reduce((a,b) => {
        let keys = Object.keys(b);
        keys.forEach(v => {
            if (Array.isArray(b[v])) a = a.concat(getKeyValues(b[v], key));
            if (v === key) a = a.concat(b[v]);
        });
        return a;
    }, [])
}

Call with

getKeyValues(arr, "keyIWant")

let arr = [{
    key: 'foo',
    values: [{
        key: 'value',
        keyIWant: 'keyIWant1'
      },
      {
        key: 'value',
        keyIWant: 'keyIWant2'
      }, {
        key: 'value',
        keyIWant: 'keyIWant3'
      }
    ]
  },
  {
    key: 'foo',
    values: [{
        key: 'value',
        keyIWant: 'keyIWant4'
      },
      {
        key: 'value',
        keyIWant: 'keyIWant5'
      }, {
        key: 'value',
        keyIWant: 'keyIWant6'
      }
    ]
  }
];

function getKeyValues(arr, key) {
  return arr.reduce((a, b) => {
    let keys = Object.keys(b);
    keys.forEach(v => {
      if (Array.isArray(b[v])) a = a.concat(getKeyValues(b[v], key));
      if (v === key) a = a.concat(b[v]);
    });
    return a;
  }, []);
}


console.log(getKeyValues(arr, "keyIWant"));

Solution 2:

We use object-scan for many data processing tasks like yours. It's powerful once you wrap your head around it. Here is how you could answer your question

// const objectScan = require('object-scan');

const find = (input) => objectScan(['**.keyIWant'], { rtn: 'value' })(input);

const arr = [{ key: 'foo', values: [{ key: 'value', keyIWant: 'keyIWant1' }, { key: 'value', keyIWant: 'keyIWant2' }, { key: 'value', keyIWant: 'keyIWant3' }] }, { key: 'foo', values: [{ key: 'value', keyIWant: 'keyIWant4' }, { key: 'value', keyIWant: 'keyIWant5' }, { key: 'value', keyIWant: 'keyIWant6' }] }];

console.log(find(arr));
/* =>
[ 'keyIWant6',
  'keyIWant5',
  'keyIWant4',
  'keyIWant3',
  'keyIWant2',
  'keyIWant1' ]
*/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I'm the author of object-scan


Post a Comment for "Find Keys In Nested Array Of Objects"