Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

javascript - Using underscore.js to compare two Objects

I'm trying to compare two objects with underscore.

Object 1 (Filter)

{
  "tuxedoorsuit":"tuxedoorsuit-tuxedo",
  "occasions":"occasions-wedding"
}

Object 2 (Properties)

{
  "tuxedoorsuit":"tuxedoorsuit-tuxedo",
  "occasions":"occasions-wedding",
  "occasions":"occasions-prom",
  "product_fit":"product_fit-slim",
  "colorfamily":"colorfamily-black"
}

I want to return true when all items of Object 1 are found within Object 2. What would be the best underscore method to use for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: As per Arnaldo's comment, you can use isMatch function, like this

console.log(_.isMatch(object2, object1));

The description says,

_.isMatch(object, properties)

Tells you if the keys and values in properties are contained in object.

If you want to iterate yourself, just use _.keys and _.every, like this

_.every(_.keys(object1), function(currentKey) {
    return _.has(object2, currentKey) &&
                    _.isEqual(object1[currentKey], object2[currentKey]);
});

Or the chained version,

var result = _.chain(object1)
    .keys()
    .every(function(currentKey) {
        return _.has(object2, currentKey) &&
            _.isEqual(object1[currentKey], object2[currentKey]);
    })
    .value();

If the result is true, it means that all the keys in object1 are in object2 and their values are also equal.

This basically iterates through all the keys of object1 and checks if the value corresponding to the key in object1 is equal to the value in object2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...