问题描述
我想检查对象属性是否可用于另一个返回 true 的对象。我试过这种方式,但它给出了错误。任何建议将不胜感激。
const checked = {0: true,1: true,2: true,3 true,4: true}
const newChecked = {0: true,3: true,4: true,5: true,6: true,7: true,8: true,9: true}
Object.entries(checked).every(e => Object.entries(newChecked).includes(e))
解决方法
如果你只想检查属性,可以使用Object.keys
来做到这一点
const checked = { 0: true,1: true,2: true,3: true,4: true };
const newChecked = {
0: true,4: true,5: true,6: true,7: true,8: true,9: true,};
const has = Object.keys(checked).every((key) =>
Object.keys(newChecked).includes(key)
);
console.log(has);
对于键值检查,可以结合使用Object.entries
和Array.prototype.findIndex
const checked = { 0: true,};
const has = Object.entries(checked).every(
([keyToFind,valueToFind]) =>
Object.entries(newChecked).findIndex(
([key,value]) => key === keyToFind && value === valueToFind
) !== -1
);
console.log(has);