How to extract node from object based on object prop?

Viewed 71

Hello everyone i have an object

const obj = {
  a: {
    uniqueId: 'u_a',
  },
  groupA: {
    uniqueId: 'u_groupA', 
    nested: {
      b: {
        uniqueId: 'u_b',
      },
      c: {
        uniqueId: 'u_c',
      },
      anotherGroup: {
        uniqueId: 'u_anotherGroup',
        nested: {
          d: {
            uniqueId: 'u_d',
          },
          e: {
            uniqueId: 'u_e',
          },
        }
      },
    }
  },
};

and i have an **array that holds the uniqueId values ** like this

[ 'u_a', 'u_b', 'u_c' ] and so on so

  1. What i want to do is loop through the array and extract the specific nodes -- for more understanding
  2. if the array is [ 'u_a' ] The result will be

const result = {
   a: {
    uniqueId: 'u_a',
  },
};

  1. And If The Array is [ 'u_b' ] the result will be

const result = {
  groupA: {
    uniqueId: 'u_groupA', 
    nested: {
      b: {
        uniqueId: 'u_b',
      },
    }
  }
};

  • And If The array is [ 'u_a', 'u_b', 'u_d' ] The result will be:

const result = {
  a: {
    uniqueId: 'u_a',
  },
  groupA: {
    uniqueId: 'u_groupA', 
    nested: {
      b: {
        uniqueId: 'u_b',
      },
      anotherGroup: {
        uniqueId: 'u_anotherGroup',
        nested: {
          d: {
            uniqueId: 'u_d',
          },
        }
      },
    }
  },
};

and So on

How can i do that

  1. List of uniqueIDs
  2. Loop through them and search for each one inside the object
  3. extract the founded node only Not All Elements

Thanks in Advance.

1 Answers

Using filterDeep from deepdash

deepdash(_);

const obj = {a:{uniqueId:"u_a"},groupA:{uniqueId:"u_groupA",nested:{b:{uniqueId:"u_b"},c:{uniqueId:"u_c"},anotherGroup:{uniqueId:"u_anotherGroup",nested:{d:{uniqueId:"u_d"},e:{uniqueId:"u_e"}}}}}}

const filter = ['u_a', 'u_b', 'u_d']

const result = _.filterDeep(obj, val => _.includes(filter, val))

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/deepdash/browser/deepdash.min.js"></script>

Related