【问题标题】:checking if Object children are null in javascript检查对象子对象在javascript中是否为空
【发布时间】:2021-06-10 18:03:06
【问题描述】:

我有一个对象,我想检查它的字段是否为空,然后我想发送一个请求。这是我的代码:

const [newProduct, setNewProduct] = useState({
    name: null,
    cost: null,
    size: null,
    color: null,
    material: null,
    discount: null,
    description: null,
    category: null
});

const addNewProduct = () => {
    if(newProduct.name && newProduct.cost && newProduct.size && newProduct.color && newProduct.material && newProduct.discount && newProduct.description && newProduct.category) {
        let productFormData = new FormData();
        productFormData.append('productInfo', JSON.stringify(newProduct));
        productFormData.append('productImages', images.imageFiles);

        const addUrl = "http://localhost:8080/cpnl/addproduct";
        axios({
            method: "POST",
            url: addUrl,
            data: productFormData,
            headers: { "Content-Type": "multipart/form-data" }
        })
            .then((response) => {
                console.log(response.data.msg);
            })
            .catch((response) => {
                console.error(response);
            });
    }
};

有没有办法让 if 语句更短? 我需要定义所有字段来修改它们吗?

【问题讨论】:

    标签: javascript json object if-statement


    【解决方案1】:
    const nulls  = Object.values(newProduct).filter(p => p === null);
    
    if (nulls.length === 0) {
       // save product
    }
    

    【讨论】:

    • 感谢您的回答。是否需要将对象字段定义为 null?
    • 在您的情况下,null 是一种说明初始数据无效的方法,如果对于此数据您有输入,则可以使用空字符串代替 null,并在过滤器中写入 p.length === 0 或p === ''
    • 不,我在单独的状态上有输入,我会将它们添加到表单提交的对象中。谢谢
    【解决方案2】:

    检查每一个对象值是否为真。

    const addNewProduct = () => {
        if (Object.values(newProduct).every(Boolean)) {
            let productFormData = new FormData();
            // ...
    

    【讨论】:

      猜你喜欢
      • 2017-08-06
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 2011-08-18
      • 2015-04-11
      • 2020-06-18
      • 2010-09-27
      • 1970-01-01
      相关资源
      最近更新 更多