[英](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. 我想知道是否有Lodash的方法来解决这个问题,否则我会用
for
循环来解决。 I would like to return true
if collection
contains one or more elements with nested object identical to c
. 如果
collection
包含一个或多个嵌套对象与c
相同的元素,我想返回true
。
The below example would return true
because collection[1]
contains an identical c
. 以下示例将返回
true
因为collection[1]
包含相同的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? 这与诸如如何用lodash进行2个对象之间的深度比较之类的问题不同。 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: 您可以在递归函数中使用
_.isEqual
:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.