【问题标题】:Vue/JS - Check if all values of two objects are nullVue/JS - 检查两个对象的所有值是否为空
【发布时间】:2021-10-20 04:58:50
【问题描述】:

我有两个对象,所有属性都设置为空。我想执行一个计算函数来检查这两个对象中的所有值是否都为空。对于一个特定的对象,我创建了以下内容: Object.values(endField.value).every(x => x === null)

我怎样才能对两个对象做同样的事情而不会在我的代码中过于重复?

const startField = ref({ date: null, month: null, year: null })
const endField = ref({ date: null, month: null, year: null })

// If the properties of both objects are all null, isEmpty should be true.
const isEmpty = computed(() => {
    return Object.values(endField.value).every(x => x === null);
});

【问题讨论】:

  • return Object.values(endField.value).every(x => x === null) && Object.values(startField.value).every(x => x === null); ?
  • 我试过了,但是当其中一个对象不为空时它返回 false。当两个对象不再为空时,我需要它变为 false。
  • 如果其中一个对象不为空,它应该返回什么?
  • 如果其中一个对象不为空,它应该保持为真。只有两个对象都不为空时,它才能为假。
  • 然后使用 OR || 而不是 AND &&

标签: javascript vue.js vuejs3


【解决方案1】:

可能是这样的:

const startField = ref({ date: null, month: null, year: null })
const endField = ref({ date: null, month: null, year: null })
const objs = [startField.value, endField.value]

const isEmpty = computed(() => {
  const check = []
  objs.forEach(v => {
     check.push(Object.values(v).every(x => x === null))
  });
  return check.every(v => v === true);
});

【讨论】:

    【解决方案2】:

    这对我有用:

    如果任何属性有值,则返回 false,否则返回 true。

            const startField = ref({ date: null, month: "Aug", year: null });
            const endField = ref({ date: null, month: null, year: null });
    
            const isEmpty = computed(() => {
                return (
                    Object.values(endField.value).every((x) => x === null) ||
                    Object.values(startField.value).every((x) => x === null)
                );
            });
    

    【讨论】:

    • @thelandog 上述更改有帮助吗?
    猜你喜欢
    • 2014-09-01
    • 2021-05-01
    • 1970-01-01
    • 2020-05-12
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    相关资源
    最近更新 更多