gpt4 book ai didi

javascript - JS 检查 2 个对象的相互项

转载 作者:行者123 更新时间:2023-12-03 12:17:54 25 4
gpt4 key购买 nike

我有 2 个 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] = trueTwo.Sunday[2] = true,我想知道这一点。

我希望我说得足够清楚。

如果可能的话,如果同一个函数也可以接受 3 个或更多对象并返回所有对象的共同项,那就太好了。

谢谢,鲁文

最佳答案

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

关于javascript - JS 检查 2 个对象的相互项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com