我有两个JS对象:
第一个:
One = {
"Sunday": {
1:false,
2:false,
3:true,
4:false, .... until 24. Each item could be either true or false.
},
"Monday": {1:true, 2:false, ....},
//And so on, 7 days of the week
}
第二个就像第一个只有它的值(真/假)不同。
我想运行一个可以告诉我的功能,我不关心两个对象中哪些项目true
。例如,如果One.Sunday[2] = true
和Two.Sunday[2] = true
,我想知道。
我希望我足够清楚。
如果可能的话,如果相同的函数也可以接受3个或更多对象并返回所有对象的共同项,那将是很好的。
谢谢,Reuven
答案 0 :(得分:1)
var sundayOne = {1:true,2:false,3:false,4:true};
var mondayOne = {1:true,2:true,3:false,4:false};
var tuesdayOne = {1:false,2:false,3:true,4:true};
var one = {"sunday":sundayOne,"monday":mondayOne,"tuesday":tuesdayOne}; // two objects having
var sundayTwo = {1:true,2:true,3:true,4:true};
var mondayTwo = {1:false,2:false,3:false,4:false};
var tuesdayTwo = {1:true,2:true,3:true,4:true};
var two = {"sunday":sundayTwo,"monday":mondayTwo,"tuesday":tuesdayTwo};
var matchedArr = []
for(each in one) {
var obj = {} //create new object
obj[each] = {} //add new object to store matched each - Sunday, Monday
for(subEach in one[each]) {
//value is false so we have to check with undefined
if(two[each][subEach] != undefined) {
if(one[each][subEach] == two[each][subEach]) {
console.log('Match found at ', each, subEach, one[each][subEach])
obj[each][subEach] = one[each][subEach]
}
}
}
matchedArr.push(obj)
}
console.log(matchedArr)
//output
[Object, Object, Object]
0: Object
sunday: Object
1: true
4: true
1: Object
monday: Object
3: false
4: false
2: Object
tuesday: Object
3: true
4: true
length: 3
答案 1 :(得分:0)
我在这里工作的对象数组会返回一个相互的数组。
两个对象
var sunday = {1:true,2:false,3:false,4:true};
var monday = {1:true,2:true,3:false,4:false};
var tuesday = {1:false,2:false,3:true,4:true};
var one = {"sunday":sunday,"monday":monday,"tuesday":tuesday}; // two objects having
var two = {"sunday":sunday,"monday":monday,"tuesday":tuesday};
过滤互助: -
function getMutuals (objects) { //get an array of objects
var mutuals = [];
objects.forEach(function(obj,index){
mutuals[index] = {};
for(var key in obj){
mutuals[index][key] = []; //it will create key like sunday,monday in each obj
var day = obj[key]; // get that key
for(var i=1;i<25;i++){
if(day[i]) //if day[i] is present
mutuals[index][key].push(i); //push that i into array of day
}
}
});
return mutuals;
}
您可以使用以下
之类的对象来调用此函数var mutuals = getMutuals([one,two]);
console.log(mutuals)
答案 2 :(得分:0)
尝试:
function mutual(){
var a = arguments, o = {};
for(var i in a){
var ai = a[i];
out: for(var n in ai){
o[n] = {}
for(var q in ai[n]){
if(!ai[n][q]){
if(o[n][q]){
delete o[n][q];
}
break out;
}
o[n][q] = true;
}
}
}
for(var i in o){
var c = 0;
for(var n in o[i]){
c++;
}
if(c === 0){
delete o[i];
}
}
return o;
}
// assumes One, Two, Three, Four, Five are Objects
// use firebug for this console.log() or create loops
console.log(mutual(One, Two, Three, Four, Five));