对象比较:检查对象是否包含整个其他对象 [英] Object Comparing: check if an object contains the whole other object
问题描述
我有两个对象。他们的结构看起来有点像这样:
I have two objects. Their structure looks a bit like this:
{
education: ["school", "institute"],
courses: ["HTML", "JS", "CSS"],
Computer: {
"OS":"WXP",
"WS":"NotePad"
}
}
第二种:
{
education: ["school", "university", "institute", "collage"],
courses: ["HTML", "CSS", "JS", "Managing", "Directing"],
Computer: {
"OS":"WXP",
"WS":"NotePad",
"AV":"Avast"
},
something: function(){...},
other: "thing"
}
您可能已经注意到,第二个对象包含整个第一个对象,加上第一个对象包含的一些项目没有。
我需要比较这两个对象,并得到一个答案( true
- false
)如果第二个对象包含第一个对象的每个项目。
true
- 如果全部第一个对象的项目也在第二个对象中
false
- 如果第一个对象的至少一个项目也不在第二个,例如:如果第二个对象没有css课程。
As you may noticed, the second object containes the whole first object, plus some items that the first one doesn't have.
I need to compare these two objects, and get an answer(true
-false
) if the second objects containes every single item of the first object.
true
- if all of the items of the first object are also in the second one
false
- if at least one of the items of the first object is not also in the second one, for example: if the second object wouldn't have the "css" course.
(第一个是要求,第二个是这个人有什么。我需要检查这个人是否有所有要求)
(The first one is requirements, the second is what the person has. I need to check if the person has all of the requirements)
可以是普通的JS,jQuery,等等。我不喜欢使用服务器端语言。
Could be plain JS, jQuery, whatever. I prefer not to use server-side languages for that.
有没有办法做到这一点?
is there a way of doing that?
谢谢!
推荐答案
只需递归检查:
function isContainedIn(a, b) {
if (typeof a != typeof b)
return false;
if (Array.isArray(a) && Array.isArray(b)) {
// assuming same order at least
for (var i=0, j=0, la=a.length, lb=b.length; i<la && j<lb;j++)
if (isContainedIn(a[i], b[j]))
i++;
return i==la;
} else if (Object(a) === a) {
for (var p in a)
if (!(p in b && isContainedIn(a[p], b[p])))
return false;
return true;
} else
return a === b;
}
> isContainedIn(requirements, person)
true
对于更类似逻辑的方法数组,顺序无关紧要,添加类似
For a more set-logic-like approach to arrays, where order does not matter, add something like
a.sort();
b = b.slice().sort()
(假设可订购内容)之前数组比较循环或用非常低效的替换它
(assuming orderable contents) before the array comparison loop or replace that by the quite inefficient
return a.every(function(ael) {
return b.some(function(bel) {
return isContainedIn(ael, bel);
});
});
这篇关于对象比较:检查对象是否包含整个其他对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!