1

I want to compare some selected fields of two objects.

E.g

const a = {type: "media", value: "TV"}
const b = {type: "media", value: "TV", name: "John"}

Can we have something to compare these two object with some specific keys like

const keys = [type, value]
compare(a, b, keys);

I just need to know some best practices to handle this logic and wants to avoid simple loops. Do we have any lodash lib for that ? Or any JavaScript ES6 function.

FYI: this is just simple example my real time scenario are far very complex.

Updates: This is what I have tried

Values are coming from react state and I am building my object E.g

const myObject = {a: aVal, b: bVal, c: cVal .......}
const compareObject = compareObject.exclude(the keys which I dont need) // example

const result = isEqual(myObject, compareObject)

Thanks

2
  • what result do you expect? a boolean value? what have you tried? Commented Jan 21, 2020 at 10:36
  • Yes boolean. Let me update my question about what I have tried. Commented Jan 21, 2020 at 10:38

2 Answers 2

1

Use _.pick() to get the properties from the 2nd object (b), and then use _.isMatch() to make a partial deep comparison of the values (only the values of b that exist in a).

Note: _.isEqual() will work for nest structures as well - see the comparison between a & c.

const compare = (a, b, keys) => _.isMatch( // check deep equality
  a, // get properties from a
  _.pick(b, keys), // get properties from b
)

const a = { type: "media", value: "TV", name: { first: "John" } };
const b = { type: "media", value: "TV", name: "John" };
const c = { type: "media", value: "TV", name: { first: "John" } };

console.log(compare(a, b, ['type', 'value'])); //  true
console.log(compare(a, b, ['type', 'name']));  // false
console.log(compare(a, c, ['type', 'name']));  // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That is what I am looking for.
1

You could check every property of both objects.

const
    compare = (a, b, keys) => keys.every(k => a[k] === b[k]),
    a = { type: "media", value: "TV" },
    b = { type: "media", value: "TV", name: "John" };

console.log(compare(a, b, ['type', 'value'])); //  true
console.log(compare(a, b, ['type', 'name']));  // false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.