这就是我想要的。
var object1 = {name: 'one', psno:'34'};
var object2 = {name: 'two', psno:'34'};
var object3 = {name: 'three', psno:'345'};
var arr1 = [object1,object2,object3];
var arr2 = [object1,object2];
// solution
var names = arr1.map(function(obj) {
return obj.name;
});
var isSuperset = arr2.every(function(val) {
return names.indexOf(val) >= 0;
});
alert(isSuperset);

它返回false而不是true。哪里出错了。
答案 0 :(得分:0)
那是因为你在检查.name
时没有.indexOf
var object1 = {
name: 'one',
psno: '34'
};
var object2 = {
name: 'two',
psno: '34'
};
var object3 = {
name: 'three',
psno: '345'
};
var arr1 = [object1, object2, object3];
var arr2 = [object1, object2];
// solution
var names = arr1.map(function(obj) {
return obj.name;
});
var isSuperset = arr2.every(function(val) {
//Ive changed this line!
return names.indexOf(val.name) >= 0;
});
alert(isSuperset);
答案 1 :(得分:0)
这是一种检查对象中所有键/值匹配的方法。
// creates a hash for each object
// e.g. "name|one|psno|34"
function hash(obj) {
return Object.keys(obj).reduce(function(p, c) {
return p.concat([c, obj[c]].join('|'));
}, []).sort().join('|');
}
// returns a hashed object
function hashObject(obj) {
return hash(obj);
}
// returns a function that checks to see
// if an element is in the array
function within(arr) {
return function (el) {
return arr.indexOf(el) > -1;
}
}
// performs the check
function check(arr1, arr2) {
if (arr1.length < arr2.length) return false;
var hashedArr1 = arr1.map(hashObject);
return arr2.map(hashObject).every(within(hashedArr1));
}
var issubset = check(arr1, arr2);