Reputation: 1013
How to check if an object contains another object like
const LHS = {
a : "Something a",
b : "Something b",
c : { a : "Something a"}
}
let RHS = {
a : "Something a",
c : { a : "Something a"}
}
// How to write a function contains which replicates this behaviour
contains(LHS, RHS) // should return true
RHS = {
a : "Something a",
c : { a : "Something a"},
d : "Something d"
}
contians(LHS, RHS) // Should return false
I have abosulety no Idea how to do that. If you know some external libaries that does this please share it.
Thanks
Upvotes: 1
Views: 437
Reputation: 44087
So you want to check if all the key/value pairs within one object are also contained within another object? That's very similar to this thread, from which I found the easiest method to check is to use this answer combined with isEqual
. Yes, bringing in libraries/modules is a hassle, but regardless, it's about as optimized as this operation could be.
const LHS = {
a: "Something a",
b: "Something b",
c: {
a: "Something a"
}
}
let RHS = {
a: "Something a",
c: {
a: "Something a"
}
}
both = _.merge(_.cloneDeep(LHS), RHS);
console.log(_.isEqual(both, LHS));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
This code will duplicate the first object (LHS
) and merge that with the second (RHS
) - those should be identical if all key/value pairs in RHS
are also in LHS
.
Upvotes: 1