1

I was wondering if there is a Lodash approach to this problem, which I would otherwise solve with a for loop. I would like to return true if collection contains one or more elements with nested object identical to c.

The below example would return true because collection[1] contains an identical c.

Needle:

c = {
  x: 11,
  y: 22,
  z: 33
}

Haystack:

collection = [
  {
    a: 1,
    b: 1,
    c: {
      x: 10,
      y: 20,
      z: 30
    },
    d: 1
  },
  {
    a: 1,
    b: 1,
    c: {
      x: 11,
      y: 22,
      z: 33
    },
    d: 1
  },
  {
    a: 1,
    b: 1,
    c: {
      x: 12,
      y: 24,
      z: 36
    },
    d: 1
  }
]

This is different from questions such as How to do a deep comparison between 2 objects with lodash? because I need to check if any of the collection items contain an identical object nested within them, not compare whether two objects are identical to each other.

Thanks in advance for your help.

Rhecil Codes
  • 511
  • 4
  • 24
  • Possible duplicate of [How to do a deep comparison between 2 objects with lodash?](https://stackoverflow.com/questions/31683075/how-to-do-a-deep-comparison-between-2-objects-with-lodash) – Get Off My Lawn Nov 22 '18 at 17:37
  • Not really the same question, but `for` loop with `_.isEqual` is one way to go, unless there is a method that I have overlooked that does the iteration and comparison in one. – Rhecil Codes Nov 22 '18 at 17:46
  • That's not a single method, but you could use`_.uniq` and then compare original size and new size, and if they are different, it had duplicates – iagowp Nov 22 '18 at 17:49

1 Answers1

1

You can use _.isEqual in a recursive function:

function find(h, n) {
  if (_.isEqual(h, n)) return true;

  let found;
  if (Array.isArray(h)) {
    for (let e of h) {
      found = find(e, n);
      if (found) return found;
    }
  } else if (h instanceof Object) {
    return find(Object.values(h), n);
  }
  
  return false;
}


var c = {
  x: 11,
  y: 22,
  z: 33
};

var d = {
  x: 1111,
  y: 2222,
  z: 32223
};


var collection = [{
    a: 1,
    b: 1,
    c: {
      x: 10,
      y: 20,
      z: 30
    },
    d: 1
  },
  {
    a: 1,
    b: 1,
    c: {
      x: 11,
      y: 22,
      z: 33
    },
    d: 1
  },
  {
    a: 1,
    b: 1,
    c: {
      x: 12,
      y: 24,
      z: 36
    },
    d: 1
  }
];

console.log(find(collection, c));
console.log(find(collection, d));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
slider
  • 12,810
  • 1
  • 26
  • 42