简体   繁体   中英

(Lodash) Is there a method to check if an identical object exists (nested) in a collection?

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM